7

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?
what
  • 83
  • 1
  • 3
  • 4
    Possible duplicate of [ES6/ES2015 object destructuring and changing target variable](https://stackoverflow.com/questions/34904523/es6-es2015-object-destructuring-and-changing-target-variable) – Mark Nov 18 '17 at 23:30

3 Answers3

10

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);
Christian Santos
  • 5,386
  • 1
  • 18
  • 24
1

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"
Vijay N Rao
  • 21
  • 1
  • 7
0

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;
Hamza Ali
  • 1
  • 4