🔰iterable
an object that can iterate over itself.
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) { ... }use cases:
for (const item of iterable) { ... } // ⭐️ for-of loop
[...iterable]                        // ⭐️ spread into array elements
f(...iterable)                       // ⭐️ spread into function arguments
let [a, b, c] = iterable             // ⭐️ iterable destructuring
// ⭐️ functios that accept iterables:
Array.from(iterable/array-like)
Promise.all(iterable)iterables:
- Array, String, Set, Map, TypedArray, 
- objects returned by generator functions. 
must implement the make-iterator method named [Symbol.iterator].
some iterables only iterate once❗️
- comforming to Iterable - make-iterator method - method named - [Symbol.iterator].
- Iterable+ext (extension) - extends iterables with custom methods. 
- obj.isIterable - check if an object is iterable. 
 
- 💾 use cases - for (const value of- iterable- )- for-of loop.
- [...- iterable- ]- spread into array elements.
- f(...- iterable- )- spread into function arguments.
- const [a, b, c] =- iterable- ;- iterable destructuring.
- Array.from(- iterable- )- convert to array.
 
- special iterable 
- ✨ examples: - range() - half-open range of numbers. 
- *integers() - generate infinite iterable. 
- ClosedRange - closed range of integers. 
 
- array-likes and iterables are different things. 
- destructuring assignment can be used with iterables. 
- defining iterable (using generator function) 
const iterable = {
    // ⭐️ "make-iterator" method
    *[Symbol.iterator]() {
        yield 1; yield 2; yield 3;
    },
};more examples ...
- *integers() - generate non-negative integers. 
- Sequence - sequence of numbers. 
- Array.from() - convert iterable / array-like to array. 
- iterable protocol ( = Sequence protocol in Swift ) 
- Symbol.iterator ( = makeIterator in Swift ) 
Last updated
Was this helpful?