JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Iterables

8 April 2025 | Category:

Iterables are data structures that can be looped through using the for...of loop or other iteration methods.

In simple terms:

If you can use for...of on it, it’s an iterable.


✅ What Is an Iterable?

An object is iterable if it implements the Symbol.iterator method.

✅ Built-in Iterables in JavaScript:

  • Strings
  • Arrays
  • Maps
  • Sets
  • Typed Arrays
  • NodeLists (like DOM elements returned by querySelectorAll())

🧪 Example: Looping Through a String

let text = "Hello";

for (let char of text) {
  console.log(char);
}

Output:

H
e
l
l
o

🧪 Example: Looping Through an Array

let colors = ["red", "green", "blue"];

for (let color of colors) {
  console.log(color);
}

Output:

red
green
blue

🔧 How Iterables Work Under the Hood

Every iterable object has a default iterator method, which is accessed using:

object[Symbol.iterator]()

It returns an iterator object with a next() method.

let arr = ["a", "b", "c"];
let iterator = arr[Symbol.iterator]();

console.log(iterator.next()); // { value: "a", done: false }
console.log(iterator.next()); // { value: "b", done: false }
console.log(iterator.next()); // { value: "c", done: false }
console.log(iterator.next()); // { value: undefined, done: true }

🔄 Custom Iterable Example

You can create your own iterable objects by defining the [Symbol.iterator]() method:

const myIterable = {
  *[Symbol.iterator]() {
    yield "Hello";
    yield "World";
  }
};

for (let value of myIterable) {
  console.log(value);
}

Output:

Hello
World

🧾 Summary

FeatureDescription
IterableObject you can loop over using for...of
ExamplesString, Array, Map, Set, etc.
Custom IterablesCan be created using [Symbol.iterator]()
Use CaseUseful for loops, generators, async logic