JavaScript : Array Iteration

Array iteration is a common operation in JavaScript, allowing you to loop through the elements of an array and perform actions on each element. Here are some common techniques for iterating over arrays:

1. for Loop:


You can use a standard for loop to iterate over the elements of an array by accessing each element using its index.


let fruits = ['apple', 'banana', 'orange', 'grape'];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

 

2. forEach() Method:


The forEach() method executes a provided function once for each array element.


let fruits = ['apple', 'banana', 'orange', 'grape'];
fruits.forEach(function(fruit) {
  console.log(fruit);
});

 

3. map() Method:


The map() method creates a new array by calling a provided function on every element in the calling array.


let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(function(num) {
  return num * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8, 10]

 

4. filter() Method:


The filter() method creates a new array with all elements that pass the test implemented by the provided function.

 

let numbers = [1, 2, 3, 4, 5];
let evens = numbers.filter(function(num) {
  return num % 2 === 0;
});
console.log(evens); // Output: [2, 4]

 

5. reduce() Method:


The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.


let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15

 

6. for...of Loop:


The for...of loop iterates over iterable objects (including arrays), allowing you to loop through the elements directly.


let fruits = ['apple', 'banana', 'orange', 'grape'];
for (let fruit of fruits) {
  console.log(fruit);
}

 

These are some common techniques for iterating over arrays in JavaScript. Depending on your specific requirements, you can choose the appropriate method or combination of methods to iterate over arrays efficiently.