How to Use For Each Over an Array in JavaScript – Definitive Guide

There are several ways available to loop through an array, among which, forEach is the commonly used one.

You can use For each over an array in JavaScript using the syntax array items.forEach(function(value, index)){<Func Definition>}.

Basic Example

array_name.forEach(function(value, index)){

//Do something during each iteration

}
  • value – current value
  • index – array index (optional)

This tutorial teaches you how to use for each over an array in JavaScript.

For Each loop over an Array

for each loop is used to loop through the objects in the JavaScript array. forEach() method was introduced in ES5 and is included under Array.Prototype.

Return Value

It returns an undefined object. You can use the callback function to perform operations on the items in the array while looping through it.

Use forEach loop in cases when the looping requirements are simpler and when minimal control over the loop is required.

Syntax

array_items.forEach(function(value, index, array) {
   // code block
 });
  • forEach method can be used only with arrays, maps, lists and sets.
  • It cannot iterate over an object, HTML collection and classes.
  • Implement Iterable to use forEach with objects or HTML collections.

The main advantage of using forEach over for loop is to optimize the code.

Using For Each With Callback Function

A callback function is a function that is passed to another function as a parameter.

forEach loop provides individual access to all the items in the array via a call back function.

Syntax

array_items.forEach(function(value, index, array) { // code block });
  • value – Value of the item during each iteration
  • index – index of the currently iterated item
  • array – The actual array object

Code

The following code iterates the array with three items and logs it in the console.

let array_items = ['one', 'two', 'three'];

//Here, function(value, index) is a callback function

array_items.forEach(function(value, index) {

  console.log(`${index}: ${value}`);

});

Output

0: one
1: two
2: three

Using For Each With Arrow Function

The arrow function is considered an alternative syntax for a function expression. It can be used as a callback function which reduces the code length.

  • => is used to create an arrow function.

Syntax

values.forEach(item => console.log(item));

Code

let array = ['one', 'two'];

array.forEach(item => console.log(item));

Here => is the arrow function that is followed by the callback function.

Output

one

two

Using For Each With Callback Function Defined Elsewhere

Sometimes you may have defined a function elsewhere in your code.

You can invoke that function inside the forEach.

Syntax

values.forEach(callback_function);

Code

let ary = ['one', 'two', 'three'];

console.log('The elements present in the array are');

 //displayval is the callback function that is defined outside of forEach

 function displayVal(array1) {
   console.log(array1); 
 }

//Using the callbackfucntion defined above. 
 ary.forEach(displayval);

Output

The elements present in the array are

one

two 

three

Tracking the Index Value using Callback Function

You can specify the index variable in the callback function to view the index of the array item during each iteration.

  • Use the index variable to track the index

Syntax

function callback_fun(value, index){

} 

Code

    let ary = ['Axe', 'Ball', 'Car'];
    console.log('The elements present in the array are');

// Function to iterate an array and log it in the console
    function displayVal(arr, index) {
      console.log(`${index} ${arr}`); 
    }

    ary.forEach(displayval);

Output

    The elements present in the array are
    0 Axe
    1 Ball
    2 Car

forEach Over An Array of Objects

forEach cannot iterate over an object by default.

To iterate over array of objects,

  • Convert the array of objects into an array list
  • Use forEach to iterate over the array of objects.

You can use object.keys , object.values and object.entries to create an array list of objects.

forEach over object.keys

The function returns the array of object’s values.

Syntax

Object.keys(obj_var).forEach(callback function);

Code

let ob = {
  a: 'js',
  b: 'owl'
};

// Prints "a" "js" and in the next line as "b" "owl"
Object.keys(ob).forEach(key => {
  console.log(key, ob[key]);
});

Output

"a" "js"
"b" "owl"

forEach Over Object.values

The function returns the array of object’s values.

Syntax

Object.values(obj_var).forEach(callback function);

Code

 let ob = {
      a: 'js',
      b: 'owl'
    };

    // Prints "js" and in the next line as "owl"
    Object.values(ob).forEach(val => {
      console.log(val);
    });

Output

"js"
"owl"

forEach over object.entries

The function returns the array of the object’s entries(Both keys and values).

Syntax

Object.entries(obj_var).forEach(callback function);

Code

 let ob = {
      a: 'js',
      b: 'owl'
    };

    // Prints "a" "js" and in next line as "b" "owl"
    // k - key; val - value 
    Object.entries(ob).forEach(entry => {
      let [k , val] = entry;
      console.log(k , val);
    });

Output

"a" "js"
"b" "owl"

forEach – Use Cases

forEach loop is used in cases

  • When you want to iterate over the items of an array.
  • When the items in an array are to be serially executed.
  • When you want to perform an operation over all the items of the array.

Comparison between forEach method and for loop

forEach methodfor loop
Accepts callback functionDo not accept callback function
Suitable for synchronous codeSuitable for synchronous and asynchronous code
The function is iterated over each itemThe entire code is enclosed inside the main body
Suitable for writing customisable codeSuitable for writing customizable code
All the main browsers except IE8 supports forEach loopfor loop is supported by all the browsers
To break a forEach loop, an exception must be thrown. Cannot use break command. break command can be used to break the for loop

JSfiddle

The tutorial is available in this JSFiddle.

Additional Resources

Leave a Comment