JavaScript: Iterable Object
New in JS2015.
Purpose of Iteratable Object
- An iterable object can hold special values to be iterated over using for-of Loop. Items iterated over are not necessarily properties. It can be characters in string, or items in Map Object, or anything the iteratable object is designed for, such a list of prime numbers.
- An iterable object's items can be turned into an array, or function arguments, by using Spread Operator.
- An 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 an object that has (own or inherited) property Symbol.iterator
.
In practice, it just means you can use for-of Loop or Spread Operator or Array.from on it.
Here is what it means:
- Symbol is a new type of value in JS2015.
- The
Symbol
is a function object.Symbol()
returns a value of type 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 symbol.) - Objects can use the value of
Symbol.iterator
as a property key. For example,obj_name[Symbol.iterator] = β¦
. - The value of
obj_name[Symbol.iterator]
must be a function that returns a Iterator. - Any object that has a property key of
Symbol.iterator
is called iterable.
console.log( Symbol.hasOwnProperty("iterator"), ); console.log( (typeof Symbol.iterator) === "symbol", );
For example, array is iterable object. Because it has inherited property key Symbol.iterator
.
const aa = [3, 4, 5]; // array has an inherited property key Symbol.iterator console.log(Reflect.has(aa, Symbol.iterator)); // not its own property console.log( aa.hasOwnProperty(Symbol.iterator) === false, ); // the property Symbol.iterator of array is inherited from Array.prototype console.log( Reflect.apply( Object.prototype.hasOwnProperty, Array.prototype, [Symbol.iterator], ), );
Test If Object is Iterable
Standard Iterable Objects
Standard objects that are iterables include: String, Array, Set, Map.
const is_iterable = ((x) => (Reflect.has(x, Symbol.iterator))); console.log( is_iterable(String.prototype), is_iterable(Array.prototype), is_iterable(Set.prototype), is_iterable(Map.prototype), );
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 .