AppDividend
Latest Code Tutorials

Javascript Foreach Example | Javascript Array forEach()

1

Javascript array forEach() is an inbuilt function that executes the provided function once for each array item. The forEach() array method is used to iterate through each item in an array. When using forEach, we have to specify a callback function. This callback function will be executed on each item in the array.

The method is called on the array Object and is passed the function that is called on each item in the array. It can only be used on the Arrays, Maps, and Sets.

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 forEach

The syntax for the forEach Javascript function is the 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 the 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.

#Javascript array forEach() example

An Array.forEach() function calls the provided function once for each element of the array.

The provided function may perform any operation on the elements of the given array. 

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 the 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 the 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, then the forEach method is not an option here. You can use it for() loop here.

#If an array is modified during 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. 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 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 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 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 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) ✗

In this example, the function forEach() adds every element to the new array.

#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.

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

Recommended Posts

Javascript array map()

Javascript array filter()

Javascript array reverse()

Javascript array reduce()

Javascript array includes()

1 Comment
  1. Amit Parmar says

    thanks for the post

Leave A Reply

Your email address will not be published.

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