I have a problem, or more some weird situation. I am using https://es6console.com.
I want to use destructuring and assign properties to already declared variables. It looks like that there is a problem in where I declare object. Please open https://es6console.com/jm6e72c7/ and click Transform to ES5. There is a weird behaviour where I declare object after variables.
// not working
let ip, port;
let config = {
ip: 'ip',
port: 'port'
}
({ip, port} = config)
console.log(ip);
//working
let obj = {
name: 'name',
age: 'age'
}
let name, age;
({name, age} = obj)
console.log(name);
First off, they both work. You have two different ways to compile ES6 code to ES5:
The result, in both cases, is that the variables are set to the appropriate values from the object.
The difference is that the transpiler thinks the return value of the assignment operation might be important in the first case, but won't be in the second case. So in the first case, you'll see
_config
at the end as the return value. It isn't needed, actually, but the transpiler is defensive -- it will do its best to make sure the functionality is exactly the same.As to why it thinks that you might want the return value in the first case, it's because of the missing semi-colon after the declaration of the
config
object.With the semi-colon added, it works as expected:
Working example