1

I am currently learning JS here and have the following code, but I do not understand why it is returning the name property.

let {name} = {name: "Faraji", age: 23};
console.log(name);
// → Faraji

And when I remove the curly braces from the variable name, I get [object Object]. Why?

let name = {name: "Faraji", age: 23};
console.log(name);
// → [object Object]

And when I access the age property with the braces I get undefined. Why?

let {name} = {name: "Faraji", age: 23};
console.log(name.age);
// → undefined

And accessing age without the braces returns undefined, too. But why?

let name = {name: "Faraji", age: 23};
console.log(name.age);
// → undefined

Whereas changing name to name1 works as expected. Thats nice.

let name1 = {name: "Faraji", age: 23};
console.log(name1.age);
// → 23
Yousaf
  • 27,861
  • 6
  • 44
  • 69
Woww
  • 344
  • 2
  • 10
  • 4
    Take a look at [Destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) – Yousaf Jul 21 '20 at 10:48
  • 2
    I cannot reproduce the 4th example `let name = {name: "Faraji", age: 23}; console.log(name.age);`, it prints 23 (instead of undefined) – Jan Stránský Jul 21 '20 at 10:54
  • 1
    4th code snippet logs the `age` correctly instead of logging `undefined`. – Yousaf Jul 21 '20 at 10:55
  • 1
    `let {name} = {name: "Faraji", age: 23};` This is object property destructuring assignment. This is syntactic sugar for: `let name = {name: "Faraji", age: 23}.name` In English, you can think of it as "take the property name (or names) enclosed in curly braces on the LHS (left hand side). For each of these values, look up the property value of the object on the RHS (right hand side). Create new variables with the LHS defined names and assign the RHS property lookup values to said variables" – mistahenry Jul 21 '20 at 10:57
  • @Yousaf Yes, it does. Thank you :) – Woww Jul 21 '20 at 10:59
  • @Yousaf Yes, it seems that my sandbox did not update correctly. – Woww Jul 21 '20 at 11:00
  • @mistahenry thank you. As a beginner such an answer helps me the most :) – Woww Jul 21 '20 at 11:01

1 Answers1

2

Its because with curly braces it becomes create a destructuring. Otherwise in order to access the object values you need to call object associated with that property.

    let  {name, age } = {name: "Faraji", age: 23};
    console.log(name, age);

Destructuring is the process of splitting and object with their keys.

let name = {name: "Faraji", age: 23};
console.log(name.name, name.age);
Santosh
  • 3,477
  • 5
  • 37
  • 75