-3

Here is a simple exercise that i don't finish to understund:

  const myObj = {
       name: 'Max', 
       age: 28
    }

    const {name} = myObj; 
    console.log(name); // prints 'Max'
    console.log(age); // prints undefined
    console.log(myObj); // prints {name: 'Max', age: 28} 

This is an exercise i found in a course i'm taking. The problem is that when i try the exercise in JSBin it only works console.log(name); the other two prints return this error:

"Max"
"error"
"@cotehixumi.js:24:1

Any help? Thanks!

Carlos Pérez
  • 167
  • 1
  • 10
  • 1
    "_Why console.log(age) prints undefined?_" Because of `const {name} = myObj;` You only asked for the `name` variable from `myObj`. – takendarkk May 12 '20 at 18:32
  • You need to destructure all the properties from myObj that you are going to use. You only destructured name and so you're able to successfully log it. – Lakshya Thakur May 12 '20 at 18:32

1 Answers1

1

When you do const {name} = myObj; You are using the spread operator. What it is basically doing is const name = myObj["name"]. The reason age is undefined is because it isn't taking the age from myObj.

If you want to fix this, just do const {name,age} = myObj;

programmerRaj
  • 1,810
  • 2
  • 9
  • 19