🔰iterable

an object that can iterate over itself.

JSiteration ⟩ 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