JavaScript Loops
Learn how to execute a block of code multiple times using for, while, do...while, for...of, and for...in loops with practical examples.
Reading Time
20 min
Lesson
Lesson 9 of 48
What are Loops?
Loops allow you to execute the same block of code multiple times without writing duplicate code. They are commonly used to process arrays, repeat tasks, and automate repetitive operations.
Why Use Loops?
- Avoid writing repetitive code
- Process arrays and objects
- Generate patterns
- Automate repetitive tasks
- Improve code readability
The for Loop
The for loop is the most commonly used loop. It consists of initialization, condition, and increment/decrement expressions.
for Loop Example
Console Output
Click “Run” to see the console output here.
The while Loop
The while loop keeps executing as long as the specified condition is true. It is useful when the number of iterations is unknown.
while Loop Example
Console Output
Click “Run” to see the console output here.
The do...while Loop
Unlike the while loop, the do...while loop executes the code block at least once before checking the condition.
do...while Example
Console Output
Click “Run” to see the console output here.
The for...of Loop
The for...of loop is used to iterate over iterable objects such as arrays and strings.
for...of Example
Console Output
Click “Run” to see the console output here.
The for...in Loop
The for...in loop is used to iterate over the keys of an object.
for...in Example
Console Output
Click “Run” to see the console output here.
break Statement
The break statement immediately terminates a loop when a specific condition is met.
break Example
Console Output
Click “Run” to see the console output here.
continue Statement
The continue statement skips the current iteration and moves to the next iteration of the loop.
continue Example
Console Output
Click “Run” to see the console output here.
Comparison of JavaScript Loops
| Loop | Best Used For |
|---|---|
| for | Known number of iterations |
| while | Unknown number of iterations |
| do...while | Run at least once |
| for...of | Arrays & Strings |
| for...in | Objects |
Best Practices
Use for...of for arrays, for...in for objects, avoid infinite loops, and always ensure your loop condition eventually becomes false.
Common Mistake
Forgetting to update the loop variable can cause an infinite loop, making your program unresponsive.
Infinite Loop Example
Console Output
Click “Run” to see the console output here.
Summary
JavaScript provides multiple looping statements including for, while, do...while, for...of, and for...in. Choosing the correct loop improves readability and performance.