Loops in JavaScript
for, while, do-while, for...of, and for...in
Understanding Loops in JavaScript
In programming, we often need to repeat a set of instructions until a condition is met. Loops help us do just that — efficiently and elegantly. JavaScript provides several types of loops, each suitable for specific use cases.
Why Use Loops?
Imagine printing a message 100 times or processing each item in a list. Writing repetitive lines of code would be inefficient and error-prone. Loops let you:
- Run the same code multiple times
- Iterate over arrays or objects
- Automate tasks in your logic flow
The for
Loop
The most common loop in JavaScript. Ideal when you know how many times to repeat the code.
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
How it Works
i = 1
is the initializer. i <= 5
is the condition. If true, the loop runs. After each iteration, i++
increments i
by 1. The loop stops when the condition is false.
The while
Loop
Used when you don't know how many times to repeat — the condition is checked before the loop body runs.
let count = 1;
while (count <= 3) {
console.log("While Loop Run:", count);
count++;
}
While Loop Run: 1
While Loop Run: 2
While Loop Run: 3
The do...while
Loop
This loop guarantees at least one execution, as the condition is checked after the loop body.
let x = 5;
do {
console.log("Do-While Value:", x);
x--;
} while (x > 3);
Do-While Value: 5
Do-While Value: 4
The for...of
Loop
Perfect for looping over array values or iterable objects.
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log("Color:", color);
}
Color: red
Color: green
Color: blue
The for...in
Loop
Used to iterate over the enumerable properties of an object (like keys).
const user = { name: "Alex", age: 30, city: "Berlin" };
for (const key in user) {
console.log(key + ":", user[key]);
}
name: Alex
age: 30
city: Berlin
Loop Control Statements
Break
Exits the loop immediately.
for (let i = 0; i < 10; i++) {
if (i === 4) break;
console.log("Break Example:", i);
}
Break Example: 0
Break Example: 1
Break Example: 2
Break Example: 3
Continue
Skips to the next iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log("Continue Example:", i);
}
Continue Example: 1
Continue Example: 2
Continue Example: 4
Continue Example: 5
Nested Loops
Loops inside loops are useful for multi-dimensional arrays or grid-like structures.
for (let i = 1; i <= 2; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`i=${i}, j=${j}`);
}
}
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
Real-World Example: Summing Numbers in an Array
const nums = [10, 20, 30, 40];
let sum = 0;
for (let num of nums) {
sum += num;
}
console.log("Total Sum:", sum);
Total Sum: 100
When to Use Which Loop?
for
– when the number of iterations is known.while
– when the condition controls the flow.do...while
– when you must run the loop at least once.for...of
– for arrays and iterables.for...in
– for object properties.
Common Mistakes and Tips
- Forgetting to update the loop counter — this can lead to infinite loops.
- Confusing
for...of
withfor...in
— they serve different purposes. - Use
break
andcontinue
wisely for better control and performance.
Comments
Loading comments...