Loops in JS
Loops in JavaScript are used to execute a block of code repeatedly until a specified condition is met.
π₯ for
Loop
π₯ while
Loop
π₯ do...while
Loop
π₯ for...in
Loop
π₯ for...of
Loop
π₯ Nested Loop
π₯ break
and continue
Statements
Executes a block of code a specified number of times.
For example:
for (let i = 0; i < 5; i++) {
console.log(i); // Output: 0, 1, 2, 3, 4
}
Repeatedly executes a block of code while a specified condition is true.
For example:
let i = 0;
while (i < 5) {
console.log(i); // Output: 0, 1, 2, 3, 4
i++;
}
Similar to while loop, but the block of code is executed at least once, even if the condition is false.
For example:
let i = 0;
do {
console.log(i); // Output: 0
i++;
} while (i < 0);
Iterates over the properties of an object.
For example:
const person = { name: 'John', age: 30, job: 'Developer' };
for (let key in person) {
console.log(key, person[key]); // Output: name John, age 30, job Developer
}
Iterates over the values of an iterable object (arrays, strings, etc.).
For example:
const colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(color); // Output: red, green, blue
}
Using loops within loops.
For example:
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(i, j); // Output: 0 0, 0 1, 0 2, 1 0, 1 1, 1 2, 2 0, 2 1, 2 2
}
}
break
: Terminates the loop.
continue
: Skips the current iteration and moves to the next one.
For example:
for (let i = 0; i < 5; i++) {
if (i === 3) break;
console.log(i); // Output: 0, 1, 2
}
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i); // Output: 0, 1, 3, 4
}