Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassign JavaScript variable via destructuring [duplicate]

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?

like image 472
Brady Dowling Avatar asked Jan 01 '23 19:01

Brady Dowling


1 Answers

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 );
like image 68
abhinav Avatar answered Jan 14 '23 05:01

abhinav