JavaScript Loops
1. For Loop
Syntax
for (initialization; condition; increment) {
// code to be executed
}
- Initialization: Usually used to declare and initialize a counter variable.
- Condition: The loop continues to run as long as this condition evaluates to true.
- Increment/Decrement: Updates the counter variable after each iteration.
Example
for (let i = 0; i < 5; i++) {
console.log(“Iteration number ” + i);
}
Output
Iteration number 0
Iteration number 1
Iteration number 2
Iteration number 3
Iteration number 4
2. While Loop
The while loop repeats a block of code as long as the specified condition remains true. It is often used when the number of iterations isn’t known in advance.
Syntax
while (condition) {
// code to be executed
}
let i =
0;
while (i <
5) {
console.
log(
“Iteration number “ + i);
i++;
}
Output
Iteration number 0
Iteration number 1
Iteration number 2
Iteration number 3
Iteration number 4
3. do…whileLoop
The do…while loop is similar to the while loop, but it guarantees that the code block will be executed at least once, even if the condition is false initially. The condition is checked after the block of code is executed.
Syntax
do {
// code to be executed
} while (condition);
Example
let i = 0;
do {
console.log(“Iteration number ” + i);
i++;
} while (i < 5);
Output
Iteration number 0
Iteration number 1
Iteration number 2
Iteration number 3
Iteration number 4
4. for…in Loop
The for…in loop iterates over the properties (or keys) of an object. Objects in JavaScript are collections of key-value pairs, where each key (also called a property name) is associated with a value. The for…in loop allows you to access these keys one by one.
Syntax
for (variable in object) {
// code to be executed
}
Output
name: Alice
age: 25
city: New York
5. for…of Loop
The for…of loop is used to iterate over iterable objects like arrays, strings, maps, or sets. It gives the values of the iterable, rather than its keys.
Syntax
for (variable of iterable) {
// code to be executed
}
Example
let numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number);
}
Output
1
2
3
4
5
Important tips
- The for loop is used to execute a block of code a specific number of times.
- The while loop executes a block of code as long as a specified condition is true.
- The do…while loop is similar to the while loop, but it will always execute the block of code at least once before checking the condition.
- The for…in loop is used to iterate over the properties of an object.
- The for…of loop is used to iterate over iterable objects (like arrays, strings, maps, sets, etc.).