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.

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 the above example, 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.

#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) ✗

#How To Break forEach loop in Javascript

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

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

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

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

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

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

If the reading on the MDN, it says that the function is executed for each of the elements in the array, in the ascending order. If we want to continue to the next item, that is, run the next function, you can simply 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);
      }
   };
}

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.