JS: Iterator.from

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2025)

Iterator.from(x_object)

Convert an iterable or iterator object to an iterator, with parent set to Iterator.prototype.

this is useful when you want to modify iterator with methods like map, foreach etc.

// convert an iterable to an iterator
// string is iterable

Iterator.from("abc").forEach((x) => console.log(x));
/*
a
b
c
*/
// show how a string iterator looks when printed
console.log(Iterator.from("abc"));
// Object [String Iterator] {}

Verify spec

// check result is an iterator.

// check has key "next".
console.assert(
 Reflect.has(Iterator.from("abc"), "next"),
);

// value is a function
console.assert(
 typeof Iterator.from("abc").next === "function",
);