JavaScript provides several types of loops to perform repetitive tasks, enabling efficient handling of iterations.
1. For loop: The most commonly used loop, where you define the initialization, condition, and increment/decrement in a single statement.
javascript
for (let i = 0; i < 5; i++) {
console.log(i);
}
2. While loop: Repeats as long as the condition is true. It checks the condition before each iteration.
javascript
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
3. Do…while loop: Similar to the while loop, but it executes the block first, then checks the condition afterward.
javascript
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
4. For…in loop: Iterates over the properties of an object.
javascript
const obj = {a: 1, b: 2};
for (let key in obj) {
console.log(key, obj[key]);
}
5. For…of loop: Iterates over iterable objects (e.g., arrays).
javascript
const arr = [1, 2, 3];
for (let value of arr) {
console.log(value);
}
These loops help efficiently handle repetitive tasks in JavaScript.