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?
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With