JavaScript: Iterable
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 is what it means:
- Symbol is a new type of value in JS2015. [see Symbol Tutorial]
- The
Symbol
is a function object.Symbol()
returns a value that has type of symbol. - The function object
Symbol
has many properties. - One of
Symbol
's property key is"iterator"
, and its value is a symbol. (that is, the type ofSymbol.iterator
is a symbol.) - Objects can use the value of
Symbol.iterator
as a property key. For example,obj_name[Symbol.iterator] = β¦
. - Any object that has a property symbol of
Symbol.iterator
is 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 Symbol.iterator
.
// 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:
console.log( [String, Array, Set, Map] .every (x => (typeof x.prototype[Symbol.iterator] === "function" )) ); // true
The Iterable Interface
Technically, any object that conforms to the Iterable Interface is called Iterable. To fully understand iterable, you need to understand JavaScript Interface.
Define Your Own Iterable Object
You can easily create your own iterable object using Generator Function. [see Generator Function]
test if a object is iterable
To test if something is iterable, check for the existence of own property
Symbol.iterator
, using
Reflect.has
const x1 = [3,4,5]; console.log(Reflect.has(x1, Symbol.iterator)); // true const x2 = { a: 3, b: 4 }; console.log(Reflect.has(x2, Symbol.iterator)); // false