JavaScript: Loops
JavaScript Loops
1 Overview
📘 Loops
Loops are used to repeat the same code multiple times. JavaScript provides several loop structures: the while
loop for repeating code while a condition is true, the do...while
loop for executing code at least once before checking the condition, and the for
loop for iterating a specific number of times. Loops can be controlled with break
(exit loop) and continue
(skip to next iteration) statements.
2 The “while” Loop
The while
loop has the following syntax:
While the condition
is truthy, the code
from the loop body is executed.
2.1 Example
A single execution of the loop body is called an iteration. The loop above makes three iterations.
2.2 Condition Evaluation
Any expression or variable can be a loop condition, not just comparisons. The condition is evaluated and converted to a boolean by while
.
A shorter way to write while (i != 0)
is while (i)
:
2.3 Single Statement
If the loop body has a single statement, we can omit the curly braces (though not recommended):
3 The “do…while” Loop
The condition check can be moved below the loop body using the do...while
syntax:
The loop will first execute the body, then check the condition, and while it’s truthy, execute it again and again.
3.1 Example
3.2 When to Use
This form of syntax should only be used when you want the body of the loop to execute at least once regardless of the condition being truthy.
Usually, the other form is preferred: while(...) {...}
.
4 The “for” Loop
The for
loop is more complex, but it’s also the most commonly used loop.
4.1 Syntax
4.2 Example
4.3 Parts of the for Loop
Part | Description | Example |
---|---|---|
begin | Executes once upon entering the loop | let i = 0 |
condition | Checked before every loop iteration | i < 3 |
body | Runs again and again while condition is truthy | alert(i) |
step | Executes after the body on each iteration | i++ |
4.4 Loop Algorithm
Run begin
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ ...
That is, begin
executes once, and then it iterates: after each condition
test, body
and step
are executed.
4.5 Step-by-Step Execution
// for (let i = 0; i < 3; i++) alert(i)
// run begin
let i = 0
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// ...finish, because now i == 3
4.6 Inline Variable Declaration
The “counter” variable i
is declared right in the loop. This is called an “inline” variable declaration. Such variables are visible only inside the loop.
4.7 Using Existing Variable
Instead of defining a variable, we could use an existing one:
5 Skipping Parts
Any part of for
can be skipped.
5.1 Omitting begin
5.2 Omitting step
This makes the loop identical to while (i < 3)
.
5.3 Omitting everything
This creates an infinite loop. The two for
semicolons ;
must be present, otherwise there would be a syntax error.
6 Breaking the Loop
Normally, a loop exits when its condition becomes falsy. But we can force the exit at any time using the special break
directive.
The break
directive is activated at line (*)
if the user enters an empty line or cancels the input.
6.1 Infinite Loop + break
The combination “infinite loop + break as needed” is great for situations when a loop’s condition must be checked not in the beginning or end of the loop, but in the middle or even in several places of its body.
7 Continue to the Next Iteration
The continue
directive is a “lighter version” of break
. It doesn’t stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows).
7.1 Example: Output Odd Numbers
For even values of i
, the continue
directive stops executing the body and passes control to the next iteration of for
.
7.2 Alternative Without continue
From a technical point of view, this is identical to the example above. But using continue
helps avoid extra nesting.
8 Labels for break/continue
Sometimes we need to break out from multiple nested loops at once.
A label is an identifier with a colon before a loop:
8.1 Example
The break outer
looks upwards for the label named outer
and breaks out of that loop.
8.2 continue with Labels
9 Loop Comparison
Loop Type | When to Use |
---|---|
while | When you don’t know how many iterations you need |
do…while | When you need at least one iteration |
for | When you know how many iterations you need |
10 Examples
10.1 Example 1: Sum Numbers
10.2 Example 2: Factorial
10.3 Example 3: Countdown
10.4 Example 4: Input Validation
10.5 Example 5: Multiplication Table
10.6 Example 6: Find First Even Number
10.7 Example 7: Skip Multiples of 3
10.8 Example 8: Nested Loops - Pattern
10.9 Example 9: Prime Number Checker
10.10 Example 10: FizzBuzz
11 Summary
- while – The condition is checked before each iteration
- do…while – The condition is checked after each iteration (executes at least once)
- for – The condition is checked before each iteration, with additional settings
- Use
break
to exit a loop immediately - Use
continue
to skip the current iteration and move to the next one - Labels allow breaking out of nested loops
- Infinite loops can be created with
while (true)
orfor (;;)
- Always ensure your loops have a termination condition to avoid infinite loops
- Choose the appropriate loop type based on your needs