JavaScript while Loop
Subject: JavaScript
The while loop in JavaScript allows you to repeatedly execute a block of code as long as a specified condition remains true. It’s especially useful when the number of iterations isn't known in advance.
Syntax
- The condition is checked before each iteration.
- If it's true, the loop body executes.
- If it's false, the loop stops.
Example 1: Basic While Loop
Example 2: Countdown Using While
Example 3: Infinite Loop (Use Cautiously)
⚠️ Be careful: An infinite loop can freeze your browser or crash your script.
Example 4: Using continue Inside a While Loop
When to Use a while Loop
- When you don't know ahead of time how many times to run.
- When you're waiting for a condition to be met.
- Useful in scenarios like polling APIs, validating user input, or simulating long-running processes.
Key Takeaways
- The
whileloop runs as long as the condition evaluates to true. - You must update the loop variable to avoid infinite repetition.
- Use
breakto exit early andcontinueto skip specific iterations. - Ideal for cases where loop conditions are dynamic or unpredictable.