There are several approaches to iteration:
for ... inand
for ... ofloops for object iteration
forEachfor array iteration (and
reduce, etc. for array transformation)
forEachand array transformations are slightly more idiomatic than loops, since they express the developer's intent more clearly. However, loops perform faster.
do while loops.
We can use
break to exit the loop immediately or
continue to advance to the next iteration. Nested loops can be labeled.
These have essentially the same syntax and work the same way as in other C-like languages.
For ... of
We can use a
for ... of loop to iterate through values within an object.
We do this most commonly with arrays, but many standard library objects can be iterated this way.
We can also define custom iteration behavior.
For ... in
for ... in loop iterates through the keys of an object.
However, it also includes inherited properties, which is often not what we want.
Due to historical complexities,
for ... inloops aren't very common.
If we do want to use a
for ... in loop, we can use the
hasOwnProperty method to filter inherited properties.
Modifying the prototype of a class will modify key lookup behavior for every object, and is something you should almost never do. However, it's possible that a library may do it (possibly by mistake), so it's still something to watch out for.
forEach to call a function for each element of an array. The function is also passed the element, the element's index, and the array itself.
We'll generally use this instead of
for ... of, unless we need to exit the loop early (i.e.
break doesn't exist in