Iterators and Generators
Iterables
An object is deemed iterable if it has an implementation for theSymbol.iterator
property.Some built-in types likeArray
,Map
,Set
,String
,Int32Array
,Uint32Array
, etc. have theirSymbol.iterator
property already implemented.Symbol.iterator
function on an object is responsible for returning the list of values to iterate on.
Iterable
interface
Iterable
is a type we can use if we want to take in types listed above which are iterable. Here is an example:
ts
functiontoArray<X>(xs:Iterable<X>):X[] {return [...xs]}
for..of
statements
for..of
loops over an iterable object, invoking theSymbol.iterator
property on the object.Here is a simplefor..of
loop on an array:
ts
letsomeArray = [1,"string",false];for (letentryofsomeArray) {console.log(entry);// 1, "string", false}
for..of
vs.for..in
statements
Bothfor..of
andfor..in
statements iterate over lists; the values iterated on are different though,for..in
returns a list ofkeys on the object being iterated, whereasfor..of
returns a list ofvalues of the numeric properties of the object being iterated.
Here is an example that demonstrates this distinction:
ts
letlist = [4,5,6];for (letiinlist) {console.log(i);// "0", "1", "2",}for (letioflist) {console.log(i);// 4, 5, 6}
Another distinction is thatfor..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 likeMap
andSet
implementSymbol.iterator
property allowing access to stored values.
ts
letpets =newSet(["Cat","Dog","Hamster"]);pets["species"] ="mammals";for (letpetinpets) {console.log(pet);// "species"}for (letpetofpets) {console.log(pet);// "Cat", "Dog", "Hamster"}
Code generation
Targeting ES5
When targeting an ES5-compliant engine, iterators are only allowed on values ofArray
type.It is an error to usefor..of
loops on non-Array values, even if these non-Array values implement theSymbol.iterator
property.
The compiler will generate a simplefor
loop for afor..of
loop, for instance:
ts
letnumbers = [1,2,3];for (letnumofnumbers) {console.log(num);}
will be generated as:
js
varnumbers = [1,2,3];for (var_i =0;_i <numbers.length;_i++) {varnum =numbers[_i];console.log(num);}
Targeting ECMAScript 2015 and higher
When targeting an ECMAScript 2015-compliant engine, the compiler will generatefor..of
loops to target the built-in iterator implementation in the engine.
The TypeScript docs are an open source project. Help us improve these pagesby sending a Pull Request ❤
Last updated: Oct 06, 2025