Use forEach over for loop

Use forEach over for loop

Prefer forEach over for loop for simple iterations:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(number => console.log(number));

The forEach method is called on the numbers array. The first argument to forEach is a callback function, which is executed for each element in the array. The callback function takes a single argument, which represents the current element in the array being processed. In this case, the argument is named number, and its value is logged to the console.

Here’s another example that demonstrates how you can use forEach to modify the elements in an array:

const numbers = [1, 2, 3, 4, 5];

const double = [];

numbers.forEach(function(number) {

  double.push(number * 2);

});

console.log(double);

// Output: [2, 4, 6, 8, 10]

In this example, the forEach method is used to iterate over the numbers array and create a new array double that contains the double of each element in numbers. The push method is used to add each doubled number to the double array.

You can also use an arrow function as the callback function for forEach:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(number => console.log(number));

// Output:

// 1

// 2

// 3

// 4

// 5

In this example, the arrow function number => console.log(number) is used as the callback function for forEach. The arrow function has a single parameter number and logs it to the console.

Note that the forEach method does not return a value and does not modify the original array. If you need to modify the original array, you should use a for loop or other iteration method.

In conclusion, the forEach method is a convenient and efficient way to iterate over an array and perform a specific action for each element. It is a powerful tool for processing arrays in JavaScript and can be used in a variety of situations to simplify your code.