Iteration in JavaScript refers to the process of repeatedly executing a block of code for each element in a collection, or until a condition is met.
1. Iteration Methods in JavaScript:
forLoopwhileLoopdo...whileLoopfor...ofLoopfor...inLoop- Array Iteration Methods (
forEach,map,filter, etc.)
2. for Loop:
The for loop is one of the most commonly used loops in JavaScript for running a block of code a specific number of times.
for (let i = 0; i < 5; i++) {
console.log("Iteration " + i);
}
Output:
Iteration 0 Iteration 1 Iteration 2 Iteration 3 Iteration 4
3. while Loop:
The while loop continues to execute as long as the specified condition is true.
let i = 0;
while (i < 5) {
console.log("Iteration " + i);
i++;
}
Output:
Iteration 0 Iteration 1 Iteration 2 Iteration 3 Iteration 4
4. do...while Loop:
The do...while loop executes the block of code at least once before checking the condition.
let i = 0;
do {
console.log("Iteration " + i);
i++;
} while (i < 5);
Output:
Iteration 0 Iteration 1 Iteration 2 Iteration 3 Iteration 4
5. for...of Loop:
The for...of loop iterates over iterable objects such as arrays and strings, accessing each value directly.
let fruits = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
Output:
Apple Banana Cherry
6. for...in Loop:
The for...in loop iterates over the enumerable properties of an object, accessing the keys.
let person = { name: "John", age: 30 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
Output:
name: John age: 30
7. Array Iteration Methods:
forEach Method:
Executes a provided function once for each array element.
let numbers = [1, 2, 3, 4];
numbers.forEach(function(number) {
console.log(number);
});
Output:
1 2 3 4
map Method:
Creates a new array populated with the results of calling a provided function on every element in the calling array.
let numbers = [1, 2, 3, 4];
let squares = numbers.map(function(number) {
return number * number;
});
console.log(squares);
Output:
[1, 4, 9, 16]
filter Method:
Creates a new array with all elements that pass the test implemented by the provided function.
let numbers = [1, 2, 3, 4];
let evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evenNumbers);
Output:
[2, 4]
Conclusion:
- JavaScript offers a variety of iteration methods to suit different use cases, whether iterating over arrays, objects, or other data structures.
- Choosing the appropriate loop or iteration method can improve code readability and performance.
- Understanding how each loop works is essential for efficient coding and problem-solving.