Reputation: 41
Why do test1
and test2
get the value undefined
in this code?
let car={id:10,style:'go'};
let {test1,test2}=car;
console.log(test1,test2);
Upvotes: 1
Views: 69
Reputation: 1074038
Your variables get the value undefined
because your object doesn't have properties called test1
and test2
. As with any other time you ask an object for a property it doesn't have, the result is the value undefined
. If you want to get the values of properties using different names from the variable names, you have to be explicit:
let {id: test1, style: test2} = car;
// ^^^ ^^^^^^
Live Example:
let car = {id:10,style:'go'};
let {id: test1, style: test2} = car;
console.log(test1, test2);
Or, of course, use the shorthand form and make the variable names match the property names:
let {id, style} = car;
Live Example:
let car = {id:10,style:'go'};
let {id, style} = car;
console.log(id, style);
You're probably confused because array destructuring is positional, but object destructuring is name-based. The name of the variable makes no difference in array destructuring:
const array = [1, 2, 3];
const [one, two] = array;
console.log(one, two);
That's because the two forms of destructuring are fundamentally different in nature. Arrays are ordered collections of elements, so array literals and array destructuring patterns both use positional notation. Objects are not, so object literals and object destructuring patterns use name-based notation (primarily). (Although "own" object properties do have a defined order in ES2015+, fundamentally objects are not ordered collections of information and it's usually not best practice to use the order that's defined.)
It's not as well known as it probably should be that the form you used in the question is actually a shorthand form for:
let {id: id} = car;
// ^^ ^^--- target variable name
// \------ source property name
This is because, again, object destructuring syntax is intentionally identical to object literal syntax, it's just on the other side of the assignment. You're probably used to things like this initializing an object property from a variable in an object literal:
let id = 42;
let obj = {id: id};
// ^^ ^^--- source variable name
// \------ target property name
console.log(obj.id); // 42
...and may know that ES2015 introduced a shorthand form for it:
let id = 42;
let obj = {id};
console.log(obj.id); // 42
The form you were using in your question is the shorthand form, in the destructuring pattern rather than the object literal.
Upvotes: 3