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

It’ll iterate over each object and applies the callback function defined inside it.

In this tutorial, you’ll look at how to use forEach over an array in javascript and access items in the array.

If You’re in Hurry…

You can use the below code snippet to use for each over an items in JavaScript.

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

}

value – current value
index – array index (optional)

If You Want to Understand Details, Read on…

forEach is one of the widely supported loop for arrays in all the browsers except IE8.

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

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.

It returns undefined object.

Hence, you can use the callback function to perform operations on the items in the array.

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. You can make them implement Iterable to use forEach with objects or HTML collection.

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

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

The syntax for javascript forEach loop is as follows

Syntax

array_items.forEach(function(value, index, array) { // code block });

Here, the parameters index and array are optional.

The below code iterates the array with three items and log it in the console.

Code

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 Arrow Function

Arrow function is considered an alternative syntax for function expression. It can be used as 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 Callback Function Defined Elsewhere

The callback function can also be defined outside of the forEach loop and it can be referred inside the forEach loop.

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.

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.

You can convert the array of bjects into an array list and then use forEach to iterate over array of objects in javascript.

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 objects entries.

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.

Conclusion

In this tutorial, you have learnt how to use for Each over an array in Javascript to iterate over the array.

You’ve also learned how to use av arrow function and callback function in the foreach loop.

If you have any questions, please comment below.

You May Also Like

Leave a Comment