ES6 - Array forEach method

ES6 JavaScript

In this ES6 tutorial we are going to learn about the array forEach method. So, let's get started.

Just like the map method which we saw in one of the previous tutorial, the forEach method also iterates over all the elements of the array and executes the provided function once for each element.

Point to note. The forEach method does not return any new array.

Print all the elements of an array

Let's say we have an array of 5 integer values and we want to print all the elements. We can do this using the for loop like the following.

const arr = [1,2,3,4,5];
for(let i = 0; i < arr.length; i++) {
  console.log(arr[i])
}

Or we can achieve the same result using the forEach method like the following.

const arr = [1,2,3,4,5];
arr.forEach(v => console.log(v));

Loop array of object using forEach

Let's say we have an array consisting of objects that represents users and we want to print username and their online status. We can solve this using the forEach method like the following.

const users = [
  { username: 'tom', isOnline: true, score: 10 },
  { username: 'jerry', isOnline: true, score: 12 },
  { username: 'tintin', isOnline: true, score: 20 }
];

users.forEach(user => {
  const { username, isOnline } = user;
  console.log(`username = ${username} isOnline = ${isOnline}`);
});

Alright, we have reach the end of another interesting tutorial. Hope to see you again in the next one. Have fun learning.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT