Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to Use forEach() to Iterate Through Arrays in JavaScript

In this blog post, we'll learn how to use the forEach() method to loop or iterate through arrays in JavaScript. This tutorial is aimed at beginners who are learning programming, and we'll try to avoid using jargons. If we use any technical terms, we'll be sure to explain them as we go along.

What is an Array?

An array is a data structure that holds a collection of elements, which can be of any data type (strings, numbers, objects, etc.). In JavaScript, arrays are ordered, meaning that their elements have a specific sequence. Arrays are also indexed, meaning that you can access an element with a numeric index that starts from zero.

Here's a simple example of an array in JavaScript:

let fruits = ['apple', 'banana', 'cherry'];

In this example, we created an array called fruits that contains three elements: 'apple', 'banana', and 'cherry'.

What is forEach()?

forEach() is a built-in method in JavaScript that we can use to loop through or iterate over the elements of an array. The forEach() method takes a callback function as its argument, and it applies this callback function to each element in the array.

The callback function can take up to three arguments:

  1. The current element being processed in the array.
  2. The index (position) of the current element in the array.
  3. The array on which forEach() was called.

Here's a simple example of how to use forEach() in JavaScript:

let fruits = ['apple', 'banana', 'cherry'];

fruits.forEach(function (fruit, index) {
  console.log(`Element ${index} is ${fruit}`);
});

In this example, we created a function that takes two arguments: fruit and index. Inside the function, we use the console.log() method to print the index and the value of each element in the fruits array.

When we run this code, we get the following output:

Element 0 is apple
Element 1 is banana
Element 2 is cherry

How to Use forEach() with Arrow Functions

An arrow function is a more concise way to write a function in JavaScript. It uses the => syntax instead of the function keyword. Here's how we can rewrite our previous example using an arrow function:

let fruits = ['apple', 'banana', 'cherry'];

fruits.forEach((fruit, index) => {
  console.log(`Element ${index} is ${fruit}`);
});

As you can see, the code is more concise and easier to read when using arrow functions. The output is the same as before:

Element 0 is apple
Element 1 is banana
Element 2 is cherry

Modifying Array Elements using forEach()

We can also use the forEach() method to modify the elements in an array. Let's say we want to add an exclamation mark to each element in the fruits array. Here's how we can do that using forEach():

let fruits = ['apple', 'banana', 'cherry'];

fruits.forEach((fruit, index, array) => {
  array[index] = fruit + '!';
});

console.log(fruits); // Output: ['apple!', 'banana!', 'cherry!']

In this example, we added a third argument to our callback function: array. Inside the function, we update the value of the current element by adding an exclamation mark to it.

Using forEach() with Objects

Although forEach() is specifically designed for arrays, we can also use it with objects by converting the object's properties into an array.

Let's say we have the following object:

let fruitColors = {
  apple: 'red',
  banana: 'yellow',
  cherry: 'red',
};

We can use the Object.entries() method to convert this object into an array of key-value pairs, like this:

let fruitColorsArray = Object.entries(fruitColors);
console.log(fruitColorsArray);

The output will be:

[
  ['apple', 'red'],
  ['banana', 'yellow'],
  ['cherry', 'red'],
]

Now that we have an array, we can use the forEach() method to iterate through its elements:

fruitColorsArray.forEach(([fruit, color]) => {
  console.log(`${fruit} is ${color}`);
});

The output will be:

apple is red
banana is yellow
cherry is red

Conclusion

In this blog post, we've learned how to use the forEach() method in JavaScript to iterate through arrays. We've also seen how to modify array elements using forEach() and how to use it with objects by converting them into arrays.

The forEach() method is a powerful and concise way to loop through arrays in JavaScript, and it's a great tool to have in your programming toolkit.

Remember that practice makes perfect, so try using the forEach() method in your own projects to become more comfortable with it. Happy coding!