Loops in JavaScript are used to repeatedly execute a block of code until a specified condition is met. They are essential for handling repetitive tasks efficiently. JavaScript provides several types of loops, each suitable for different scenarios.
The for
loop is ideal when the number of iterations is known beforehand.
for (initialization; condition; increment/decrement) {
// Code to execute
}
- Initialization: Initializes a counter variable.
- Condition: Determines how long the loop runs.
- Increment/Decrement: Updates the counter variable after each iteration.
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4
The while
loop executes the code block as long as the specified condition evaluates to true
.
while (condition) {
// Code to execute
}
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// Output: 0, 1, 2, 3, 4
This loop guarantees at least one execution of the code block, even if the condition is false
initially.
do {
// Code to execute
} while (condition);
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
// Output: 0, 1, 2, 3, 4
This loop is designed for iterating over iterable objects like arrays, strings, Maps, or Sets.
for (variable of iterable) {
// Code to execute
}
let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
// Output: apple, banana, cherry
The for...in
loop iterates over the enumerable properties of an object. It’s often used for objects rather than arrays.
for (variable in object) {
// Code to execute
}
let car = { brand: "Tesla", model: "Model 3", year: 2023 };
for (let key in car) {
console.log(`${key}: ${car[key]}`);
}
// Output:
// brand: Tesla
// model: Model 3
// year: 2023
Loop Type | Use Case | Example |
---|---|---|
for |
When the number of iterations is known in advance. | Iterating over a range of numbers. |
while |
When the condition depends on dynamic factors or external input. | Waiting for user input. |
do...while |
When you need to execute a block at least once before checking the condition. | Menu-based applications. |
for...of |
When working with iterables (arrays, strings, etc.). | Iterating over an array. |
for...in |
When iterating over the properties of an object. | Reading object properties. |
- Use
for
loops when dealing with numerical ranges or index-based operations. - Use
for...of
loops for simpler syntax when iterating over arrays or other iterables. - Avoid
for...in
loops for arrays as they might include unintended inherited properties. - Always include a termination condition to prevent infinite loops.
- Infinite Loops: Forgetting to update the loop variable or write the exit condition correctly.
let i = 0; while (true) { // Infinite loop console.log(i); }
- Using
for...in
on Arrays:let arr = [1, 2, 3]; for (let index in arr) { console.log(index); // Logs the indices as strings, not the values. }
Loops are versatile constructs in JavaScript that help automate repetitive tasks. By understanding the differences and applications of each type, you can select the right loop for your specific use case and write efficient, readable code.