DEV Community

Chloe
Chloe

Posted on

for of, for in or forEach?

I've been going over a few array methods to refresh some of them and this is one thing I've never fully grasped. There are for of loops and for in what is the use case for these?

In addition, you also have forEach what are the key differences? Is it performance or personal preference? I don't really understand the difference between them could someone point me in the right direction?

Top comments (3)

Collapse
 
ryands17 profile image
Ryan Dsouza

for of loops are used for data structures that can be iterated over (iterables). Arrays and strings are examples of such structures. So if I have something like this:

let arr = [1, 2, 3, 4, 5]

for (let i of arr) console.log(i)

Would give me all the elements in that array.

for in on the other hand is used for objects, where I want to loop over an object literal.

let obj = { id: 1, name: 'abc }

for (let key in obj) console.log(key, obj[key])

Will list out the keys and corresponding values of the given object.

forEach is also used to loop over arrays but takes a function instead.

let arr = [1, 2, 3, 4, 5]

arr.forEach(number => console.log(number))

The advantage of for of would be that you can use keywords like break and continue to alter the flow which is not possible with forEach.

Collapse
 
emma profile image
Emma Goto πŸ™

I personally use forEach loops wherever possible. The only time I will need to use a for loop will be if I need to break out of a loop early (e.g. I'm looping through until I find a specific element, and then stopping).

Collapse
 
mnlfischer profile image
Manuel • Edited

The for and for/in looping constructs give you access to the index in the array, not the actual element.

With forEach() and for/of, you get access to the array element itself.

Note:

  • forEach keeps the variable’s scope to the block
  • lower chance of accidental errors with forEach
  • forEach is easier to read
  • you can break out of a for loop earlier