Skip to main content

JavaScript Iterables

By SamK
0
0 recommends
Category(s)
Topic(s)

In this tutorial, you'll learn about iterables in JavaScript.

JavaScript Iterables

In JavaScript, iterables are objects that allow iteration over their values using simple and efficient code. Examples of iterables include arrays, strings, sets, and maps. Iterables can be looped through using the for..of loop.

The For..Of Loop

The for..of loop iterates through the values of an iterable object.

Syntax:

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

Iterating Over a String

const name = "Web";
for (const char of name) {
 console.log(char);
}

// Output:
W
e
b

Iterating Over an Array

const colors = ["Red", "Green", "Blue"];
for (const color of colors) {
 console.log(color);
}

// Output: 
Red
Green
Blue

Iterating Over a Set

const uniqueNumbers = new Set([1, 2, 3, 4]);
for (const num of uniqueNumbers) {
 console.log(num);
}

// Output: 
1
2
3
4

Iterating Over a Map

const fruits = new Map([
 ["Apples", 5],
 ["Bananas", 10],
 ["Oranges", 7]
]);
for (const [fruit, quantity] of fruits) {
 console.log(`${fruit}: ${quantity}`);
}

// Output: 
Apples: 5
Bananas: 10
Oranges: 7

JavaScript Iterators

An iterator is an object that produces a sequence of values when its next() method is called. Each call returns an object with two properties:

  • value - The current value
  • done - Boolean (true if iteration is complete, false otherwise)

Simple Iterator

function createIterator() {
 let count = 0;
 return {
   next: function() {
     count += 5;
     return { value: count, done: count > 20 };
   }
 };
}
const iterator = createIterator();
console.log(iterator.next()); // { value: 5, done: false }
console.log(iterator.next()); // { value: 10, done: false }
console.log(iterator.next()); // { value: 15, done: false }
console.log(iterator.next()); // { value: 20, done: false }
console.log(iterator.next()); // { value: 25, done: true }

Questions & Answers