Loops are one of the most important concepts in JavaScript. They allow you to run the same block of code multiple times without writing it again and again. This makes your code shorter, cleaner, and more efficient.
In this tutorial, you’ll learn:
-
What loops are in JavaScript
-
Why loops are used
-
Types of loops in JavaScript
-
Code examples with clear explanations
What Are Loops in JavaScript?
A loop is a programming structure that repeats a set of instructions until a specific condition is met.
Example use cases:
-
Printing numbers from 1 to 10
-
Looping through an array
-
Repeating an action until a condition becomes false
Why Use Loops?
Without loops, you would need to write the same code multiple times.
Loops help to:
-
Reduce code repetition
-
Save development time
-
Improve readability
-
Handle large data efficiently
Types of Loops in JavaScript
JavaScript mainly provides these loops:
-
forloop -
whileloop -
do...whileloop -
for...ofloop -
for...inloop
1. for Loop in JavaScript
The for loop is used when you know in advance how many times the loop should run.
Syntax
Example
Explanation
-
let i = 1→ loop starts from 1 -
i <= 5→ loop runs while condition is true -
i++→ increases value ofiby 1 each time -
Output will be numbers from 1 to 5
2. while Loop in JavaScript
The while loop runs as long as the condition is true.
Syntax
Example
Explanaion
-
Condition is checked before loop execution
-
Loop stops when condition becomes false
3. do...while Loop in JavaScript
The do...while loop executes the code at least once, even if the condition is false.
Syntax
Example
Explanation
-
Code runs once before condition check
-
Useful when execution is required at least one time
4. for...of Loop in JavaScript
The for...of loop is used to iterate over values of iterable objects like arrays and strings.
Example with Array
Explanation
-
Directly accesses array values
-
Cleaner and easier than traditional
forloop
5. for...in Loop in JavaScript
The for...in loop is used to iterate over object properties.
Example
Explanation
-
keyrepresents object property name -
user[key]gives property value
Common Loop Mistakes to Avoid
-
Forgetting to update loop variable (infinite loop)
-
Using
for...infor arrays instead of objects -
Incorrect loop condition
When to Use Which Loop?
| Situation | Recommended Loop |
|---|---|
| Fixed number of iterations | for |
| Condition-based execution | while |
| Must run at least once | do...while |
| Iterating array values | for...of |
| Iterating object properties | for...in |
Conclusion
Loops are a core building block of JavaScript programming. Understanding different types of loops helps you write efficient and readable code. Start with the for loop, then gradually move to advanced loops like for...of and for...in.