I am trying destructuring assignment in JavaScript but its giving undefined

36 Views Asked by At

const myObj = {
    name: "Rahul",
    age: 34,
    Roll: 23
}
// console.log(myObj)

const {x, y, z} = myObj;
console.log(x)

I tried to store values of myObj in these three variables using the destructuring assignment but its giving undefined.

2

There are 2 best solutions below

0
zb22 On

You use destructuring assignment this way:

const myObj = { name: "Rahul", age: 34, Roll: 23 }
const {name, age, Roll} = myObj;

but if you want to rename the variables with x, y and z you can do this:

const myObj = { name: "Rahul", age: 34, Roll: 23 }
const {name: x, age: y, Roll: y} = myObj;

Destructuring assignment

0
AudioBubble On

you can destructure something like this

const {name:x, age:y, Roll:x } = myObj;

You are trying to access x,y and z which are not the properties of your object