AppDividend
Latest Code Tutorials

Javascript Array forEach() Method Example

0

Javascript array foreach is an inbuilt function that can be used to execute a function on each item in the array. The forEach() method is called on the array Object and is passed the function that is called on each item in the array.  The callback function can also take the second parameter of the index in case you need to reference the index of the current element in the array.

Understanding Javascript Array forEach

In a nutshell, Javascript forEach() method executes a provided function once for each array element. Javascript forEach only be used on the Arrays, Maps, and Sets. This article briefly describes how to use the forEach() method to iterate the items of the array in JavaScript.

What’s the usual thing you do with an array? Add or remove items from an array. Iterate through its items! This is where the forEach() array method shines.

Before we dive into seeing how forEach() works, we need to take a look at how looping works. Looping is a fundamental computer science concept. If you want to be a sound programmer, mastering loops are amidst the first steps you need to take.

Here’s an example of a for loop in Javascript.

let languages = ['Python', 'Javascript', 'PHP', 'Golang'];

for (i = 0; i < languages.length; i++) {
  console.log(languages[i])
}

Output

Python
Javascript
PHP
Golang

As you can see, a for loop allows us to execute a specific block of code; however, many times we want. In this case, we looped through the list of languages and printed the names.

After ES6, we don’t need to use for loop to access the element one by one and perform the specific operations. To iterate each item in the array, we can use a Javascript array forEach() function and perform the required operation on them.

We can get the same output as for loop gives us using the forEach() method.

let languages = ['Python', 'Javascript', 'PHP', 'Golang'];

languages.forEach(element => {
  console.log(element)
});

Output

Python
Javascript
PHP
Golang

You can see that we get the same output. For loop consumes more time to go through each item where the forEach() function is more efficient to traverse each element of the array.

The forEach function accepts the callback function. Now, this callback function applies to all the elements of the array and gives the output.

Okay, first, we will see the syntax of the forEach() method.

Syntax

array.forEach(function(currentValue, index, array), thisValue)

Parameters

function(currentValue, index, array)

It is required, and it is a function to be run for each element in the array.

See the following Function arguments:

currentValueRequired. The value of the current element.
indexOptional. The array index of the current element.
arrayOptional. It is the array object the current element belongs to.

 

thisValue

The thisValue parameter is Optional. It is the value to be passed to the function to be used as its “this” value.
If this parameter is empty, then the value “undefined will be passed as its “this” value.

Example

Let us take an example of the forEach function.

Create one file called server.js and open that file inside VSCode. Write the following code in the server.js file.

// server.js

const apps = ['WhatsApp', 'Instagram', 'Facebook'];
const playStore = [];

apps.forEach(function(item){
  playStore.push(item)
});

console.log(playStore);

Javascript Foreach Example

So, here first, we have taken an array of apps. Then we have iterate the array one by one using forEach and add the items one by one to the new array called playstore and display it.

Array.prototype.forEach()

The prototype constructor allows us to add new properties and methods to the Array() Object itself.

There are already some methods available in the Javascript, and one of them is forEach. 

When constructing the property, All arrays will be given the property, and its value, as default. When constructing a method, All arrays will have this method available. A prototype is a global object constructor which is available to all the Javascript objects. Let us take an example of that.

// server.js

function Square() {
  this.squareArray = [];
}
Square.prototype.multiply = function(arr) {
  arr.forEach(function(value) {
    this.squareArray.push(value * value);
  }, this);
};

const obj = new Square();
obj.multiply([2, 5, 9]);
console.log(obj.squareArray);

Accessing an index of an iterated element in forEach()

If you see the syntax of forEach() function, you can see that callback() function accepts an argument called index. So, now we can get the current iterating element’s index using that parameter.

let languages = ['Python', 'Javascript', 'PHP', 'Golang'];

languages.forEach((element, index) => {
  console.log('The element is: ', element)
  console.log('The element\'s index is:', index)
});

Output

The element is:  Python
The element's index is: 0
The element is:  Javascript
The element's index is: 1
The element is:  PHP
The element's index is: 2
The element is:  Golang
The element's index is: 3

You can see that Python’s index is 0 because the array index starts from 0. Then 1, 2, and 3.

In this example, we are using an arrow function as a callback function that has access to the current iterated item and its index. The callback is executed 4 times.

There is no way to break the forEach loop other than by throwing an exception. If you need such behavior for your code, then the forEach method is not an option here. You can use it for() loop here.

Accessing the array inside the callback

We can access the array in the forEach callback. This is the same array which is currently iterated by the forEach() method. The callback function also accepts the array as an argument, and inside the function block, we can use the array.

let languages = ['Python', 'Javascript', 'PHP', 'Golang'];

languages.forEach((element, index) => {
  if (index == languages.length - 1) {
    console.log(`${element} is the last element of the iteration`)
  }
});

Output

Golang is the last element of the iteration

You can see that we have accessed the languages array inside the callback function block to compare the index with array’s last index and if both are the same, then “if condition” holds true. We logged our last element of the array iteration.

Incrementing With forEach()

We can define a counter outside the forEach() function, and then inside the function, we can increment the count with the number whatever we want, and it will increase the counter. The count operation will be incremented the exact times the length of the array items.

let languages = ['Python', 'Javascript', 'PHP', 'Golang'];
let count = 0

languages.forEach(() => {
  count = count + 2
  console.log(count)
});

Output

2
4
6
8

In this example, we have incremented the count value by 2. In the first iteration counter = 0 + 2 = 2 and then 2 + 2 = 4, 2 + 4 = 6, 2 + 6 = 8.

Compare for vs for…in() in Javascript

See the following for…in syntax.

for (variable in object) {  
  // do something
}

 The for…in loop is used to iterate over the enumerable properties of objects.

Every property in the Object will have the Enumerable value if that value is set to true, then the property is Enumerable.

When you create the Object, it will inherit specific methods from its prototype.

For instance, Javascript Object.keys() method. These are non-enumerable. Any properties you add to the Object will, for the most part, be enumerable.

Let’s look at an example to help with understanding. In the example below, we will print on the console each enumerable value in the Object.

const obj = {  
  millie: 'eleven',
  noah: 'will',
  finn: 'mike',
  sadie: 'max'
}

for (let char in obj) {  
  console.log( obj[char] )
}

 Output

➜  es git:(master) ✗ node app
eleven
will
mike
max
➜  es git:(master) ✗

Don’t forget, and arrays are objects too; that is why we can also use the for…in loop on Arrays.

Modifying array during an iteration

Let us take a scenario where we change the array, which is being iterated, and then it might skip the other values. See the following example.

// app.js

let arr = [1, 2, 3, 4, 5];

arr.forEach(item => {
    if(item == 3) {
        arr.shift();
    }
    console.log(item);
});

In the above example, if the condition fulfills, then the next element of the array is skipped.

We have used the Javascript array shift() function to skip the 3rd value.

So, when the item = 3, then 4 value is skipped, and direct go to 5.

That means, we have modified the array using our logic and skip one element, which is the violation of forEach function because it always executes on each item of an array.

iterate(keys, values) in Javascript

If we want to iterate the key-value pair in the javascript, then we forEach loop will not help us. Instead, we can use the Javascript for…in loop. See the following example.

// app.js

let strangerThings = [{
  name: 'Dustin',
  age: 13
}, {
  name: 'Mike',
  age: 12
  },
  {
    name: 'Eleven',
    age: 11
  }];

for (const name in strangerThings) {
  if (strangerThings.hasOwnProperty(name)) {
    console.log(strangerThings[name]);
  }
}

See the following output.

➜  es git:(master) ✗ node app
{ name: 'Dustin', age: 13 }
{ name: 'Mike', age: 12 }
{ name: 'eleven', age: 11 }
➜  es git:(master) ✗

this inside forEach loop

Let’s run the following code in a browser, and pay attention to the value of this.

const names = ['krunal', 'ankit', 'rushabh'];

function iterate(name) {
  console.log(this === window);
}

names.forEach(iterate);

this inside iterate() equals to the window, which is the global Object in the browser environment.

In some situations, you might need to set this to the Object of interest. Then indicate this Object as the second argument when calling forEach() function.

Javascript forEach skips empty slots.

JS forEach() skips the empty slots of the array.

const names = ["krunal", "", "ankit"];

names.forEach(function(name) {
  console.log(name);
});

Output

➜  es git:(master) ✗ node app
krunal

ankit
➜  es git:(master) ✗

The names array contains “krunal”, an empty slot, and “ankit”. JS forEach() iterates over “krunal” and “ankit”, but skips the empty slot.

How To Break forEach loop in Javascript

You can’t break from the forEach function. Instead, you should use the normal for loop.

In some cases, Array.every() function will probably fulfill the requirements.

How do I go to the next iteration of the Javascript Array.forEach() loop

You can return if you want to skip the current iteration.

Since you’re in the function, if you return before doing anything else, then you have effectively skipped the execution of the code below the return statement.

JavaScript’s forEach works a bit different from the one that might be used from other languages for each loop.

If you read on the MDN, it says that the function is executed for each of the items in the array, in the ascending order. If we want to continue to the next item, that is, run the next function, you can return a current function without having it do any computation.

Compatibility

This method is a JavaScript extension to the ECMA-262 standard; as such, it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script.

if (!Array.prototype.forEach)
{
   Array.prototype.forEach = function(fun /*, thisp*/)
   {
      var len = this.length;
      if (typeof fun != "function")
      throw new TypeError();
      
      var thisp = arguments[1];
      for (var i = 0; i < len; i++)
      {
         if (i in this)
         fun.call(thisp, this[i], i, this);
      }
   };
}

Javascript forEach() and Javascript push()

Let’s copy all the values from one array to another array using Javascript foreach function and Javascript push() function.

// app.js

const elements = [11, 21, 46];
const copy = [];

elements.forEach(function(element){
  copy.push(element);
});
console.log(copy);

See the output.

➜  es git:(master) ✗ node app
[ 11, 21, 46 ]
➜  es git:(master) ✗

Difference between forEach() and for in loop

Javascript forEach() is an Array method that we can use to execute a function on each item in an array.

Javascript for in loop is used to iterate over the enumerable properties of objects.

Every property in an object will have an Enumerable value — if that value is set to true, then the property is Enumerable.

Async function with forEach

See the following code.

let ratings = [9.1, 9.2, 9.3];

let sum = 0;

let godfather = async function(x, y) {
  return x + y;
};

ratings.forEach(async function(rating) {
  sum = await godfather(sum, rating);
});

console.log(sum);

Output

➜  es git:(master) ✗ node app
0
➜  es git:(master) ✗

 In the above code, the expected output would be 27.6, but we got 0 because of async/await.

JavaScript Array forEach() Method Main Tips

  1. The forEach() applies a specified function for each of the items individually.
  2. Introduced with ECMAScript 3.
  3. This method only executes the specified function is an array item has a value.
  4. Its return value is undefined.

Finally, the Javascript Array foreach() function Example is over.

See also

Array.prototype.find()

Array.prototype.findIndex()

Array.prototype.map()

Array.prototype.filter()

Array.prototype.every()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.