5

If I am declaring new variables in JavaScript, I can do so via destructuring as follows:

const myObj = {
  thing1: 'first thing',
  thing2: 'second thing'
};

const { thing1, thing2 } = myObj;

I'd like to do something similar but by re-assigning variables that are passed as parameters in a function (which are assigned via an implied let and therefore not static). I tried something like the following:

function myFun(thing1, thing2) {
  const myObj = {
    thing1: 'first thing',
    thing2: 'second thing'
  };

  { thing1, thing2 } = myObj;
}

This gave me an unexpected token error on the =. Is this possible or can I only declare new variables with destructuring?

Brady Dowling
  • 4,920
  • 3
  • 32
  • 62
  • Note that arguments are passed by value, so values assigned to them, in the function, will never get back to the caller. This is unrelated to whether you use destructuring or not. – trincot Jul 15 '19 at 18:32

1 Answers1

13

It is pretty simple. For the variable which are declared already and you want to reassign them values using destructuring just add the parenthesis around the statement.

( { thing1, thing2 } = myObj );
abhinav
  • 607
  • 6
  • 18
  • 1
    @NagaSaiA I didn't get what you are saying. thing1 and thing2 will have the values 'first thing' & 'second thing' . – abhinav Jul 15 '19 at 18:44
  • Thanks for the answer! But I think parentheses would be the proper term `( ... )`, not braces `{ ... }` . Although that may be a localized term. To me: parentheses ( ), brackets [ ], braces { } – bombillazo Jul 01 '21 at 22:13
  • Super late, but may I ask why this works? – Zach Jul 26 '21 at 20:49
  • @Zach This is the JS syntax to achieve this. – abhinav Nov 30 '21 at 18:13