New in ES2015.
Purpose of Iteratable
The purpose of Iteratable object is that they can be iterated over using
for-of loop, or, all items listed by using Spread Operator
Also, a iterable object can have potentially infinite number of items. As opposed to a array or map or set, which every item occupy memory.
The for-of loop is designed so that it can go over data structure properly. For example, has definite order, without going up the prototype chain, and without relying on property index or converting to array.
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 ES2015. [see JS: 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 JS: 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 [see JS: String Object]
- Array [see JS: Array Object]
- Set [see JS: Set Object]
- Map [see JS: Map Object]
console.log ( [String, Array, Set, Map] .every ((x) => (typeof x.prototype[Symbol.iterator] === "function" )) ); // true
The Iterable Interface
[see JS: Interface]
Define Your Own Iterable Object
You can easily create your own iterable object using Generator Function. [see JS: Generator Function]
JS Iterable ⭐
If you have a question, put $5 at patreon and message me.