Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is a problem with destructuring ES6 on declared object?

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);
like image 499
zamf123 Avatar asked Nov 23 '25 12:11

zamf123


1 Answers

First off, they both work. You have two different ways to compile ES6 code to ES5:

({ip, port} = config)
// converted to
((_config = config, ip = _config.ip, port = _config.port, _config));

// and

({name, age} = obj)
// converted to
name = obj.name;
age = obj.age;

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:

let config = {
    ip: 'ip',
    port: 'port'
};

({ip, port} = config)

Working example

like image 99
lonesomeday Avatar answered Nov 25 '25 00:11

lonesomeday