Iterables
loops over an iterable object, invoking the Symbol.iterator
property on the object. Here is a simple for..of
loop on an array:
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
returns a list of values of the numeric properties of the object being iterated.
Another distinction is that for..in
operates on any object; it serves as a way to inspect properties on this object. for..of
on the other hand, is mainly interested in values of iterable objects. Built-in objects like and Set
implement Symbol.iterator
property allowing access to stored values.
Code generation
Targeting ES5 and ES3
When targeting an ES5 or ES3-compliant engine, iterators are only allowed on values of Array
type. It is an error to use for..of
loops on non-Array values, even if these non-Array values implement the Symbol.iterator
property.
will be generated as:
Targeting ECMAScript 2015 and higher
When targeting an ECMAScipt 2015-compliant engine, the compiler will generate for..of
loops to target the built-in iterator implementation in the engine.