๐ฐ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โ๏ธ
an iterable can be infinite. ( ๐ see๏ผ *integers())
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