4

I'm trying to destructure an object with ES6 syntax then reassign the variable inside a loop.

ES5

this.playlist.forEach((item, i) => {
  item.timeoutId = setTimeout(() => {
    item.sound.play()
  }, 1000 * i)
})

ES6 (not working)

this.playlist.forEach(({sound, timeoutId}, i) => {
 timeoutId = setTimeout(() => {
   sound.play()
  }, 1000 * i)
})

Any idea of why it is not working?

0

2 Answers 2

5

It should work, with one caveat:

timeoutId = setTimeout(() => {
    sound.play()
}, 1000 * i)

timeoutId is the value inside item.timeoutId, and not an alias of it. When you assign a value to timeoutId, it won't be assigned back to item.timeoutId.

Using item.timeoutId to cancel the timeout, won't work, since the item.timeoutId won't contain the timeout id.

In the example, you can see that timeoutId stays null:

const arr=[{ id: 1, timeoutId: null }, { id: 2,timeoutId: null }, { id: 3, timeoutId: null }, { id: 4, timeoutId: null }];

arr.forEach(({sound, timeoutId}, i) => {
 timeoutId = setTimeout(() => {
   //sound.play()
  }, 1000 * i)
})

console.log(arr);

The solution as noted by @guest271314 is to assign to the property directly, using the the 3rd parameter of the forEach (the array), and the index:

const arr=[{ id: 1, timeoutId: null }, { id: 2,timeoutId: null }, { id: 3, timeoutId: null }, { id: 4, timeoutId: null }];

arr.forEach(({sound}, i, arr) => {
 arr[i].timeoutId = setTimeout(() => {
   //sound.play()
  }, 1000 * i)
})

console.log(arr);

Sign up to request clarification or add additional context in comments.

1 Comment

Ok so I'd better stick to ES5 syntax that is much clearer than the one with forEach 3rd parameter. Thanks for your anwser.
3

It doesn't work because your ES6 code is basically an equivalent to this code:

this.playlist.forEach((item, i) => {
  let timeoutId = item.timeoutId;
  let sound = item.sound;
  timeoutId = setTimeout(() => {
    sound.play()
  }, 1000 * i)
})

So you are just reassigning a local variable instead of an item object property.

1 Comment

Thanks, so the destructuring part act as a copy basically and not as a reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.