The syntax looks to be right off of MDN, so I'm not understanding why this object destructuring isn't working. The variables return undefined, why?
let obj={age: "3", name: "spike"};
let {a,b}=obj;//returns a and b as undefined, why?
The syntax looks to be right off of MDN, so I'm not understanding why this object destructuring isn't working. The variables return undefined, why?
let obj={age: "3", name: "spike"};
let {a,b}=obj;//returns a and b as undefined, why?
You need to use name
and age
as the variables that you destructure from the object like so:
let obj={age: "3", name: "spike"};
let {age, name}=obj;
console.log(age);
console.log(name);
Alternatively, you can assign new names to the destructured variables by using the following syntax:
let obj={age: "3", name: "spike"};
let {age: a, name: b}=obj;
console.log(a);
console.log(b);
You need to destructure using the same keys 'age' and 'name' that are in the 'obj' object. But at the same time you can assign them your own alias names like 'a' and 'b' as below.
let obj={age: "3", name: "spike"};
let {age:a, name:b}=obj;
console.log(a); //prints "3"
console.log(b); //prints "spike"
You need to pass the same variable name as they are in the object in you case it will be
let obj={age: "3", name: "spike"};
let {age,name}=obj;