JavaScript Iterables
In JavaScript, an iterable is any object that implements the iterable protocol, meaning it has a Symbol.iterator
method. This allows it to be used in loops like for...of
, spread syntax (...
), and Array.from()
.
1️⃣ What is an Iterable?
An iterable is an object that can be iterated over using a for...of
loop. Examples of built-in iterables include:
✔️ Arrays
✔️ Strings
✔️ Maps
✔️ Sets
✔️ TypedArrays
✔️ Arguments Object
✔️ NodeLists
2️⃣ Using for...of
Loop with Iterables
The for...of
loop works on iterables by calling their Symbol.iterator
method.
3️⃣ Built-in Iterables
🔹 Strings are Iterables
🔹 Arrays are Iterables
🔹 Sets are Iterables
🔹 Maps are Iterables
4️⃣ The Spread Operator (...
) with Iterables
The spread operator works on iterables to expand their contents.
5️⃣ Array.from()
with Iterables
The Array.from()
method can convert iterables into arrays.
6️⃣ Creating a Custom Iterable
We can create a custom iterable by implementing the [Symbol.iterator]()
method.
7️⃣ Generators as Iterables
Instead of manually creating an iterator, we can use generators (function*
).
8️⃣ Checking if an Object is Iterable
To check if an object is iterable, we check if it has [Symbol.iterator]
.
🎯 Summary
✔ Iterables are objects that implement [Symbol.iterator]()
✔ for...of
loop works on iterables
✔ Built-in iterables include Arrays, Strings, Maps, and Sets
✔ Spread operator (...
) and Array.from()
work with iterables
✔ Custom iterables can be created using [Symbol.iterator]()
✔ Generators (function*
) provide an easier way to create iterators
🚀 Now you understand JavaScript iterables! Let me know if you need more examples. 😊