AppDividend
Latest Code Tutorials

Javascript Array Foreach Example | Array.prototype.forEach() Tutorial

0

Javascript Array Foreach Example | Array.prototype.forEach() Tutorial is today’s leading topic. The forEach() method executes the provided function once for each array item. The ‘forEach’ array method is used to iterate through each item in an array. The 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 a second parameter of an index in case you need to reference the index of the current item in the array.

If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Javascript Array Foreach Example

The syntax for the forEach Javascript function is following.

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

The currentValue is the current item in an array that is iterating right now.

The index an optional parameter which is the current element index of an array.

The arr is an optional parameter which is an array object that is current element belongs to.

The thisValue is an optional parameter that is the value to be passed to the function to be used as its “this” value.

Array forEach() method example

Let us create a folder and inside that, create a file called app.js and add the following code.

// app.js

var arr = [1, 2, 3, 4, 5];
var newArray = [];

arr.forEach(function(item) {
    newArray.push(item + 21);
});

console.log(newArray);

In the above example, we are using forEach function to add 21 to every array item. So the newly created element looks like this.

Javascript Array Foreach Example | Array.prototype.forEach() Tutorial

 

We can write the above function in ES6 style.

// app.js

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

arr.forEach(item => newArray.push(item + 21));

console.log(newArray);

The forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined, and it is not chainable. So we can use to execute at the end of a chain.

Accessing Array Index in forEach() method

We can access the index inside the function like this.

// app.js

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

arr.forEach((item, i) => console.log(i));

Now, the output will be like this.

 

forEach method in Javascript

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

If an array is modified during iteration

Let us take a scenario, where we change the array which is being iterated 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 an above example, the if the condition fulfills then the next element of the array is skipped. 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.

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);
      }
   };
}

Finally, Javascript Array Foreach Example | Array.prototype.forEach() Tutorial is over.

Leave A Reply

Your email address will not be published.

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