end video

This lesson is only accessible in the paid version of the course.

Get access to all lessons 💫 price: 34.99$

If you already have an account click here.

§ What is iterable protocol in JavaScript and why is useful

In this video, we will explore the iterable protocol in JavaScript and how it allows objects to define their iteration behavior.

The iterable protocol in JavaScript is a mechanism that allows objects to define or customize their iteration behavior. It is implemented using the Symbol.iterator property, which is a method that returns an iterator object. This iterator object defines a next() method that returns an object with two properties: value, which is the next value in the iteration and done, which is a boolean indicating if the iteration is done.

An object is considered iterable if it defines the Symbol.iterator property. The most common examples of iterable objects in JavaScript are arrays and strings, which can be iterated using a for-of loop or the spread operator.

const myArray = [1, 2, 3];
for (const value of myArray) {
  console.log(value);
}
// Output: 1 2 3
const myString = "Hello";
for (const value of myString) {
    console.log(value);
}
// Output: H e l l o

It's also possible to create custom iterable objects by defining a Symbol.iterator method on an object. The method should return an iterator object that defines a next() method.

const myCustomIterable = {
  values: [1, 2, 3],
  [Symbol.iterator]() {
    let index = 0;
    return {
      next: () => {
        if (index < this.values.length) {
          return { value: this.values[index++], done: false };
        }
        return { done: true };
      }
    };
  }
};

for (const value of myCustomIterable) {
    console.log(value);
}
// Output: 1 2 3

In summary, the iterable protocol in javascript allows objects to define or customize their iteration behavior by implementing a Symbol.iterator property, which returns an iterator object that defines a next() method. This feature allows for a consistent way to iterate over different types of objects in JavaScript.

questionnaire

Practice

Practice is the fastest way to learn knowledge permanently. I have prepared a small task for you related to the lesson.

Practice
discussion

Materials

Materials related to the lesson:
Files associated with the lesson

Materials

Next: Generators(05:18)

To the lesson →