Summary
Both for...of
and for...in
statements iterate over lists; the values iterated on are different though, for...in
returns a list of keys on the object being iterated, whereas for...of
works on an iterable object and returns the result of the iterators implementation.
for...in
for...in
sometimes written as for-in
returns the index value for the specific loop.
If you want to gain access to the value when using for..in
on an array, you use the index of the current loop to access from the array object.
for...of
for...of
sometimes written as for-of
gives you the value returned by the iterator implementation. This can be different depending upon how the iterater was implemented. For example, the built in iterator implementation for array iterator yields all the values in the array, ignoring non-index properties.
Using Symbol.iterator
, you can create custom iterators that can be used inside of for-of
Array spreads and other iterable loops. For example, you could create a new iterator that iterated over an array in reverse.
In this example, createCustomIterator is a function that takes an array and returns an implementation iterator. It could be used on multiple arrays to reverse iterate over them.