๐Ÿ”ฐiterable

an object that can iterate over itself.

JS โŸฉ iteration โŸฉ iterable

โญ๏ธ ES6 (2015)

an object that can make iterators. (like Sequence in Swift, must implement .makeIterator() method)

for (const value of iterable) { ... }    // for-of
[...iterable]                 // spread into array elements
f(...iterable)                // spread into function arguments
const [a, b, c] = iterable;   // destructuring iterable
Array.from(iterable)          // iterable -> array

(by default) object is not iterableโ—

let obj = { x: 1, y: 2, z: 3 };
for (let value of obj) { }                   // โ›” TypeError

// โญ๏ธ workarounds
for (let key of Object.keys(obj) { ... }
for (let key in obj) { ... }                 // for-in
for (let value of Object.values(obj) { ... }
for (let [key, value] of Object.entries(obj) { ... }

๐Ÿ‘‰ for-in vs. for-of vs. in

Last updated