Skip to content

JavaScript for of vs forEach | Difference

  • by

The for and for/in looping constructs give access to the index in the array, not the actual element. For example, if want to print out the values stored in the below array you need arr[i]:

With the other two constructs, forEach() and for/of, you get access to the array element itself. With forEach() you can access the array index i, with for/of you cannot.

JavaScript for-of vs forEach code

Simple example syntax Difference.

Like the for loop, the forEach the method can also achieve the same results:

<!DOCTYPE html>
<html>
<head>
  <script>
    const foodArray = [
    { name: 'Burrito' },
    { name: 'Pizza' },
    { name: 'Burger' },
    { name: 'Pasta' }
    ];
    foodArray.forEach((food, index) => {
      console.log(`i value: ${index} | Food Name:`, food);
    });
  </script>
</head>
<body>

</body>
</html>

Output:

JavaScript for of vs forEach

forEach example

let iterable = [10, 20, 30];

iterable.forEach((val) => {
   console.log(val);
})

for of example

let iterable = [10, 20, 30];
    
for (let value of iterable) {
   console.log(value);
}

Should one use for-of or forEach when iterating through an array?

Answer: basics of both

ForEach exclusively belong to the royal family of Arrays. The forEach method was introduced with lineage to the prototypal inheritance of Array object! Needless to say, the forEach clause works only with those data structure which are Arrays. The method basically iterates over the elements of the array and executes a callback function [basically some executable function/ fun activity].

The for-of loop is adequately new to the JS world and packs in super-powers! Voilaaaaaaa! The for-of loop creates a loop iterating over iterable member objects. The list is an extensive one such as

  • Array
  • Map
  • Set
  • String
  • TypedArray
  • Other W3C classes

You need to know that this bad-ass boy emerged with the birth of ES6 in 2015. So, it offers plenty of flexibility in usage


Performance

In performance, for...of is faster than forEach. Results can be found here

forEach is 24% slower than for...of

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS comparison topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading