DEV Community

Discussion on: [JavaScript] 5 Interesting uses of JavaScript destructuring!

Collapse
 
yumatsushima07 profile image
Yuma-Tsushima

So post increment was used in the movies example .
So it adds 1 to the operator.
So if you do index++ it will log the firstvalue.
If you do ++index it will log the secondvalue

eg

const movies = {
  list: [
    { title: 'Skyfall' }, 
    { 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); // so it logs skyfall
Enter fullscreen mode Exit fullscreen mode

but once we use the pre increment it will log interstellar

const movies = {
  list: [
    { title: 'Skyfall' }, 
    { 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); // now logs interstellar 
Enter fullscreen mode Exit fullscreen mode

and if we just left it without increment then it would just be skyfall because it just logs the index.

I hope that helps.

Collapse
 
austinbooth profile image
austinbooth

Thanks for the explanation. So without the increment you wouldn’t be able to destructure further movies in the list, only the first one?

Thread Thread
 
yumatsushima07 profile image
Yuma-Tsushima

yes