TypeScript Iterators and Generators
TypeScript has some built in types like Array, String, Int32Array, Uint32Array, etc. support iteration because they have implemented Symbol.iterator property. In order to perform iteration on custom object, object must implement Symbol.Iterator
property.
TypeScript For..Of Statement
The for..of loop work with iterable object like array by invoking Symbol.Iterator
property and return value of iterable objects. For Example:
TypeScript For..Of Example 1
class Customer {
Display():number
{
let numbers = [1, 2, 3,4,5,6,7,8,9,10];
var s : any = "";
var o = 0;
for (let num of numbers) {
s = s + "\n Array Value is - " + num;
}
return s;
}
}
Try it Yourself
TypeScript For..In Statement
The for..of loop work with any iterable object and return key of iterable objects. For Example:
TypeScript For..Of Example 2
class Customer {
Display():number
{
let numbers = [1, 2, 3,4,5,6,7,8,9,10];
var s : any = "";
var o = 0;
for (let num in numbers) {
s = s + "\n Array Value is - " + num;
}
return s;
}
}
Try it Yourself
Difference between For...In
- For..In - returns a list of keys on the iterable object
- For..In - operates on any object
Difference between For...Of
- For..Of - returns a list of value on the iterable object
- For..Of - operates on any object that implement Symbol.iterator property