HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Iterables

Iterables are data structures that can be looped over (iterated) using the for...of loop. In JavaScript, several built-in objects are iterables by default, including Strings, Arrays, Sets, and Maps.


The for...of Loop

The for...of loop is the standard way to iterate over iterable objects. Its syntax is clean and it works by getting the values directly.

for (const value of iterable) {
  // code block to be executed
}

Iterating Over a String

A JavaScript string is an iterable. You can loop over it to access each character one by one.

const name = "Mim";

for (const x of name) {
  console.log(x);
}
// Output: M i m

Iterating Over an Array

Arrays are the most common iterables. for...of gives you the values rather than the indexes (unlike a traditional for loop).

const colors = ["Red", "Blue", "Green"];

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

Newer Iterables (Sets and Maps)

ES6 introduced two new data collections that are also iterables:

  • Sets: Collections of unique values.
  • Maps: Collections of key-value pairs.
// Iterating over a Set
const letters = new Set(["a", "b", "c"]);
for (const x of letters) {
  console.log(x);
}
Technical Note: For an object to be "iterable", it must implement the Symbol.iterator method. This method is called by the for...of loop to set up the iteration sequence.

Key Points to Remember

  • An iterable is an object that can be looped over
  • The for...of loop is designed specifically for iterables
  • Strings, Arrays, Sets, and Maps are all built-in iterables
  • Traditional objects {} are not iterable by default
  • for...of iterates over values, not keys or properties
  • Modern JavaScript relies heavily on iterables for efficient data processing