New in JS2015.
Purpose of Iteratable
The purpose of Iteratable object is that they can be iterated over using for-of Loop , or, all items feed into array/argument items by using Spread Operator .
Also, a iterable object can have potentially infinite number of items, computed at the time when needed. As opposed to a array, where every item already exists and occupy memory.
What is Iterable Object
A iterable object is basically any object with a
Symbol.iterator method (own property or inherited).
Here's what it means:
- Symbol is a new type of value in JS2015. [see Symbol Tutorial]
Symbolis a function object.
Symbol()returns a value that has type of symbol.
- The function object
Symbolhas many properties.
- One of
Symbol's property key is
"iterator", and its value is a symbol. (that is, the type of
Symbol.iteratoris a symbol.)
- Objects can use the value of
Symbol.iteratoras a property key. For example,
obj_name[Symbol.iterator] = ….
- Any object that has a property symbol of
Symbol.iteratoris called “iterable”.
- The value of
obj_name[Symbol.iterator]must be a function that returns a iterator. [see Iterator]
console.log( Symbol.hasOwnProperty("iterator") ); // true console.log( (typeof Symbol.iterator) === "symbol" ); // true
For example, array is iterable object. Because it has inherited property key
// array instance has inherited property key Symbol.iterator const aa = [3,4,5]; console.log( Symbol.iterator in aa ); // true // not its own property console.log( ! aa.hasOwnProperty(Symbol.iterator) ); // true // the property symbol Symbol.iterator of array is inherited from Array.prototype console.log( Reflect.apply ( Object.prototype.hasOwnProperty, Array.prototype, [Symbol.iterator] ) ); // true
Standard Iterable Objects
Standard builtin objects that are iterables include: • String • Array • Set • Map
console.log( [String, Array, Set, Map] .every (x => (typeof x.prototype[Symbol.iterator] === "function" )) ); // true
The Iterable Interface
Define Your Own Iterable Object
You can easily create your own iterable object using Generator Function. [see Generator Function]