0

I need to do ES6 Destructuring Assignment repeatedly:

  1. Define variables from Destructuring Assignment
  2. Update variables from Destructuring Assignment repeatedly

Like:

function margin() {
  const left=1, right=2, top=3, bottom=4;
  return { left, right, top, bottom };
}

let { left, bottom } = margin();

// later, need to update left, bottom again:
{ left, bottom } = margin();

How to make the above code work?
I'm getting Unexpected token when updating the variables again.

I know putting them all into a single variable will do, but the question focus on whether it is possible to use Destructuring Assignment repeatedly.

xpt
  • 20,363
  • 37
  • 127
  • 216
  • `{ left, bottom } = margin();` starts as a block statement with the no-op expression statement `left, bottom;`. The `=` after the end of the block statement is not syntactically valid. Instead of a block statement, you need a destructuring assignment expression, but in order to correctly disambiguate the `{` at the start, you need to force an [_ExpressionStatement_](//tc39.es/ecma262/#prod-ExpressionStatement) production. Parentheses are the most common way to do this: `({ left, bottom } = margin());`. Yes, it’s possible to use destructuring repeatedly, but you need to get the syntax right. – Sebastian Simon Feb 25 '23 at 19:58
  • 1
    the duplicate target has a horrible subject ... – Nina Scholz Feb 25 '23 at 19:59
  • Exactly @NinaScholz -- there is no way I can find that as my answer on my own search :(. – xpt Feb 25 '23 at 20:08
  • 1
    i changed the titel a bit. – Nina Scholz Feb 25 '23 at 20:13

0 Answers0