JavaScript Loops
Loops in JavaScript are used to repeat a block of code multiple times until a certain condition is met. They are essential for automating repetitive tasks, iterating over arrays or objects, and controlling the flow of programs efficiently.
1. for Loop
The for
loop is the most common loop in JavaScript. It is ideal when the number of iterations is known beforehand.
Syntax:
for (initialization; condition; increment/decrement) {
// code to execute
}
Example:
for (let i = 1; i <= 5; i++) {
console.log(i); // Prints 1 to 5
}
2. while Loop
The while
loop is used when the number of iterations is unknown, and you want to continue looping as long as a condition remains true.
Syntax:
while (condition) {
// code to execute
}
Example:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
3. do…while Loop
The do…while
loop is similar to while
, but the block of code executes at least once before checking the condition.
Syntax:
do {
// code to execute
} while (condition);
Example:
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
4. for…in Loop
The for…in
loop iterates over enumerable properties of an object (keys). It is not ideal for arrays if index order matters.
Syntax:
for (key in object) {
// code to execute
}
Example:
const person = {name: "Alice", age: 25, city: "Delhi"};
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Output: name: Alice, age: 25, city: Delhi
5. for…of Loop
The for…of
loop is used to iterate over iterable objects like arrays, strings, maps, sets, NodeLists, etc. It retrieves values directly, unlike for…in
which retrieves keys.
Syntax:
for (value of iterable) {
// code to execute
}
Example:
const numbers = [10, 20, 30];
for (let num of numbers) {
console.log(num); // 10, 20, 30
}
const str = "Hello";
for (let char of str) {
console.log(char); // H, e, l, l, o
}
6. Nested Loops
Nested loops occur when a loop is placed inside another loop. They are useful for multi-dimensional data structures like matrices, tables, or grids.
Syntax:
for (initialization; condition; increment) {
for (initialization; condition; increment) {
// inner loop code
}
}
Example:
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 2; j++) {
console.log(`i=${i}, j=${j}`);
}
}
// Output: i=1,j=1; i=1,j=2; i=2,j=1; i=2,j=2; i=3,j=1; i=3,j=2