JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Iterables


In JavaScript, iterables are objects that can be looped over using constructs like for...of loops. An iterable is any object that implements the iterable protocol, meaning it has a special method with the key [Symbol.iterator]. Understanding iterables is fundamental to working with arrays, strings, sets, maps, and custom objects that can be traversed sequentially.

This tutorial explains iterables in detail, their syntax, practical examples, common mistakes, best practices, and real-world applications.

What Are Iterables?

An iterable is an object that provides access to its elements one at a time, in a sequence. JavaScript treats arrays, strings, maps, and sets as built-in iterables. Iterables allow developers to:

  • Traverse data structures sequentially.

  • Use loops like for...of to access values directly.

  • Integrate seamlessly with spread syntax, destructuring, and other iterable-based operations.

  • Build custom objects that behave like arrays or strings.

In simple terms, iterables define how JavaScript should loop through an object.

The Iterable Protocol

An object is iterable if it has a [Symbol.iterator] method. This method must return an iterator object, which implements the iterator protocol. An iterator object has a next() method that returns:

{ value: ..., done: ... }
  • value – The current element in the sequence.

  • done – Boolean indicating whether the sequence is finished.

Example 1: Using Array as Iterable

let names = ["Aarushi", "Priya", "Ananya"];
for (let name of names) {
  console.log(name);
}

Output:

Aarushi
Priya
Ananya

Arrays are iterables, so the for...of loop works directly with them.

Example 2: Using String as Iterable

let word = "Isha";
for (let char of word) {
  console.log(char);
}

Output:

I
s
h
a

Strings are iterable, allowing sequential access to each character.

Example 3: Using Set as Iterable

let students = new Set(["Meera", "Saanvi", "Ananya"]);

for (let student of students) {
  console.log(student);
}

Output:

Meera
Saanvi
Ananya

Sets are iterable and ensure unique values during iteration.

Example 4: Using Map as Iterable

let studentGrades = new Map([
  ["Priya", "A"],
  ["Ananya", "B"],
  ["Isha", "A"]
]);

for (let [student, grade] of studentGrades) {
  console.log(`${student}: ${grade}`);
}

Output:

Priya: A
Ananya: B
Isha: A

Maps are iterable over key-value pairs, supporting destructuring in loops.

Custom Iterables

You can create custom objects that are iterable by implementing [Symbol.iterator].

Example 5: Custom Iterable Object

let numbers = {
  start: 1,
  end: 5,
  [Symbol.iterator]: function() {
    let current = this.start;
    let last = this.end;
    return {
      next() {
        if (current <= last) {
          return { value: current++, done: false };
        } else {
          return { done: true };
        }
      }
    };
  }
};

for (let num of numbers) {
  console.log(num);
}

Output:

1
2
3
4
5

Here, numbers behaves like an iterable object even though it’s not an array.

Using Spread Syntax with Iterables

Iterables work naturally with the spread operator:

let names = ["Aarushi", "Priya", "Ananya"];
let allNames = [...names, "Isha", "Meera"];
console.log(allNames);

Output:

["Aarushi", "Priya", "Ananya", "Isha", "Meera"]

This is useful for merging arrays or converting iterables into new arrays.

Converting Iterables to Arrays

let letters = "Ananya";
let lettersArray = Array.from(letters);
console.log(lettersArray);

Output:

["A", "n", "a", "n", "y", "a"]

Array.from() creates a new array from any iterable, allowing further array operations.

Common Mistakes

  • Assuming all objects are iterable. Regular objects are not iterable by default.

  • Forgetting to implement [Symbol.iterator] when creating custom iterables.

  • Confusing iterables with iterators. Iterables generate iterators using [Symbol.iterator].

  • Using for...of on non-iterable objects without converting them (e.g., using Object.values() first).

Best Practices

  • Use iterables with for...of for readable and concise loops.

  • Prefer arrays, sets, and maps for collections when iteration is needed.

  • Use Array.from() to convert iterables into arrays for advanced operations.

  • Implement [Symbol.iterator] when building custom iterable objects.

  • Avoid complex logic inside the iterator’s next() method to maintain readability.

Real-World Applications

  • Iterating over API response data returned as arrays or maps.

  • Processing strings for character-level operations.

  • Traversing sets for unique value operations.

  • Creating custom iterable objects for advanced data structures.

  • Combining spread syntax with iterables to merge or copy data efficiently.

Summary of JS Iterables

Iterables are a core concept in JavaScript that allow objects to be looped over in a standardized way. Built-in iterables like arrays, strings, maps, and sets can be accessed directly using for...of loops, spread syntax, and Array.from(). Developers can also create custom iterables by implementing [Symbol.iterator].

Understanding iterables helps in writing concise, readable, and efficient code for a variety of applications, from simple arrays to complex custom data structures. Proper use of iterables ensures smooth data traversal, enhanced functionality, and maintainable code.


Practice Questions

Q1. What is an iterable in JavaScript and how is it different from an array?

Q2. List some built-in JavaScript objects that are iterable.

Q3. How can you use the for...of loop to loop through a string?

Q4. What happens if you try to use for...of on a non-iterable object like {}?

Q5. How does JavaScript determine whether an object is iterable?

Q6. How can you manually iterate over an iterable using its iterator?

Q7. Write a code snippet to loop through a Set using for...of.

Q8. What is the purpose of Symbol.iterator in an iterable object?

Q9. How can you create a custom iterable using a generator function?

Q10. Explain the difference between iterable objects and array-like objects.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top