JavaScript Iteration

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:

  1. for Loop
  2. while Loop
  3. do...while Loop
  4. for...of Loop
  5. for...in Loop
  6. 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);
}

Try It Now

Output:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

Try It Now

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++;
}

Try It Now

Output:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

Try It Now

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);

Try It Now

Output:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

Try It Now

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);
}

Try It Now

Output:

Apple
Banana
Cherry

Try It Now

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]);
}

Try It Now

Output:

name: John
age: 30

Try It Now

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);
});

Try It Now

Output:

1
2
3
4

Try It Now

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);

Try It Now

Output:

[1, 4, 9, 16]

Try It Now

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);

Try It Now

Output:

[2, 4]

Try It Now

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.