Looping statements in JavaScript allow you to execute a block of code multiple times. This tutorial will cover the different types of loops available in JavaScript and provide examples for each.
JavaScript Looping Statements
1. For Loop
The for loop is used when you know in advance how many times you want to execute a statement or a block of statements.
for (let i = 0; i < 5; i++) {
console.log("Iteration: " + i);
}
This loop will output the following:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
2. While Loop
The while loop executes a block of code as long as a specified condition is true. Be careful, as it can lead to an infinite loop if the condition never becomes false.
let i = 0;
while (i < 5) {
console.log("Iteration: " + i);
i++;
}
This will produce the same output as the for loop above:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
3. Do...While Loop
The do...while loop is similar to the while loop, but it guarantees that the code block will be executed at least once, as the condition is checked after the execution of the block.
let i = 0;
do {
console.log("Iteration: " + i);
i++;
} while (i < 5);
This will also output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
4. For...of Loop
The for...of loop is used to iterate over iterable objects like arrays, strings, and other collections.
const arr = ['apple', 'banana', 'cherry'];
for (const fruit of arr) {
console.log(fruit);
}
Output:
apple
banana
cherry
5. For...in Loop
The for...in loop is used to iterate over the enumerable properties of an object.
const obj = {a: 1, b: 2, c: 3};
for (const key in obj) {
console.log(key + ": " + obj[key]);
}
Output:
a: 1
b: 2
c: 3
6. Conclusion
JavaScript provides various looping statements that enable you to execute blocks of code multiple times. Understanding the differences between these loops will help you choose the right one based on your needs.