For Of Loops
The for...of
statement creates a loop that iterates over iterable objects (Array
, Map
, Set
, arguments
, etc.). for...of
is particularly useful for iterating over other kinds of collections. cannot iterate over objects, so for...in
provides the best way to iterate over an object. For of loops were introduced in ES6. They're excellent for iterating over arrays.
For in versus For of
For in loops are best used to iterate over objects, where for of loops are great for iterating over arrays. Take the below example. I want an array of cat names, and I want to console each name and "says meow". If I try and do it in a for in loop, I won't get what I'm looking for. Take the below code.
Notice that using a for...in
loop results in the keys being printed out. So the array indexes, or keys are printed instead of the value we want.
When we use for...of
, we get the value of the items in our array printed out. This is usually what you want when iterating over an array, so for now keep in your mind that "for of" is useful for things like arrays, and "for in" is useful for objects.
Last updated