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:
letarr=[1,2,3,4,5]for(letiofarr)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.
letobj={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.
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: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.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.The advantage of
for of
would be that you can use keywords likebreak
andcontinue
to alter the flow which is not possible withforEach
.