JavaScript Iterables

JavaScript Iterables

JavaScript Iterables

 

In JavaScript, an iterable is an object that can be iterated over using the “for…of” loop or other iterable-consumer functions such as “Array.from()” and “Spread Operator”.

In order for an object to be considered iterable, it must have a special method called the “Symbol.iterator” method. This method should return an iterator object, which is an object with a “next()” method that returns the next value in the iteration sequence.

Here’s an example of an iterable object:

				
					let myIterable = {
  [Symbol.iterator]: function* () {
    yield 1;
    yield 2;
    yield 3;
  }
};

				
			

In this example, the “myIterable” object is an iterable that returns the values 1, 2, and 3 when iterated over. The “Symbol.iterator” method defines a generator function that uses the “yield” keyword to return each value in the sequence.

You can iterate over this iterable using a “for…of” loop, like this:

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

				
			

This code will output the values 1, 2, and 3 to the console, one at a time.

Other built-in iterable objects in JavaScript include arrays, strings, maps, sets, and typed arrays. These objects all have the “Symbol.iterator” method defined, so they can be iterated over using the “for…of” loop or other iterable-consumer functions.

Join To Get Our Newsletter
Spread the love