JS: Iterable Object

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

What is iterable object

An iterable object holds special values to be iterated over.

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.

Technically, any object that conforms to the Iterable Interface is called Iterable.

Example of Iterable's Values

Iterated values can be anything the iterable object is designed for, such a list of prime numbers.

How to iterate over iterable's values

Standard objects that are iterable

Array, String, Map, Set, TypedArray, and arguments object.

// string
console.assert(
 Reflect.has(new String("abc"), Symbol.iterator),
);

// array
console.assert(
 Reflect.has([1, 2, 3], Symbol.iterator),
);

// set
console.assert(
 Reflect.has(new Set(), Symbol.iterator),
);

// map
console.assert(
 Reflect.has(new Map(), Symbol.iterator),
);
// string is iterable

console.log([..."abc"]);
// [ "a", "b", "c" ]

for (let k of "abc") console.log(k);
// a
// b
// c


// but in some situations, you need to explicitly turn it into a object first
console.assert(
 Reflect.has(new String("abc"), Symbol.iterator),
);

Define your own iterable object

You can create your own iterable object using Generator Function .