DEV Community

Discussion on: for of, for in or forEach?

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.