Skip to content

Instantly share code, notes, and snippets.

@denis-shvets
Last active August 25, 2019 08:40
Show Gist options
  • Save denis-shvets/b358714164d645e7e1fbcdb1645f5d53 to your computer and use it in GitHub Desktop.
Save denis-shvets/b358714164d645e7e1fbcdb1645f5d53 to your computer and use it in GitHub Desktop.
Destructuring iterables

Destructuring iterables

In the previous sections, the destructuring was applied to arrays. But you can destructure any object that implements the iterable protocol.

Many native primitive types and objects are iterable: arrays, strings, typed arrays, sets, and maps.

For example, you can destructure a string to characters:

const str = 'cheese';

const [firstChar = ''] = str;

firstChar; // => 'c'

You’re not limited to native types. Destructuring logic can be customized by implementing the iterable protocol.

movies holds a list of movie objects. When destructuring movies, it would be great to get the movie title as a string. Let’s implement a custom iterator:

const movies = {
  list: [
    { title: 'Heat' }, 
    { title: 'Interstellar' }
  ],
  [Symbol.iterator]() {
    let index = 0;
    return {
      next: () => {
        if (index < this.list.length) {
          const value = this.list[index++].title;
          return { value, done: false };
        }
        return { done: true };
      }
    };
  }
};

const [firstMovieTitle] = movies;
console.log(firstMovieTitle); // => 'Heat'

movies object implements the iterable protocol by defining the Symbol.iterator method. The iterator iterates over the titles of movies.

Conforming to an iterable protocol allows the destructuring of movies object into titles, specifically by reading the title of the first movie: const [firstMovieTitle] = movies.

The sky is the limit when using destructuring with iterators.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment