0

I was trying to get the x and y value from obj.coords, but the value is not updated using destructuring assignment.

let obj = { name: 'test', coords: [0, 0] }
let x = 0, y = 0

obj = { ...obj, coords: [12, 16] }

// not working
[x, y] = obj.coords

console.log('coords:', x, y)

I tried assign them one by one, it works:

let obj = { name: 'test', coords: [0, 0] }
let x = 0, y = 0

obj = { ...obj, coords: [12, 16] }

// works
x = obj.coords[0]
y = obj.coords[1]

console.log('coords:', x, y)

Is there a reason for that? Or is it some kind of bug?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
hiroshi
  • 461
  • 3
  • 8
  • 10
    Add a semicolon to the line before array destructuring. Otherwise, it is interpreted as `obj = { ...obj, coords: [12, 16] }[x, y] = obj.coords`. – adiga Jun 22 '21 at 07:17
  • 4
    There is nothing destructive here, e.g. information loss. It’s not called “destructive assignment”. It’s called “destructuring”, because you’re extracting things from a structure. – Sebastian Simon Jun 22 '21 at 07:21
  • 1
    One of the few gotchas for not using the "optional" semicolons. – Ouroborus Jun 22 '21 at 07:22

0 Answers0