Using Variables to access properties of object

Hello there, I have a little problem about using variables to access properties of object

let me = {name:"alex",height:180 ,weight:90}
console.log (me.name) 

it will print out “alex” for sure

But if i let x = name and use x to assess the properties of object, it will not show “alex”

let me = {name:"alex",height:180 ,weight:90}

let x = name

console.log (me.x) 

can anyone please explain to me why me.x didn’t work ? i think it should work as x=name

I hope this helps
But declaring it in both the let me =
is basicly this

name “alex”
height 180
weight 90

me does direct it to let me
then the . which is used to connect to name
name contains alex.
me => name => alex
that’s why the 1st code works
in the second code
let x = name
I get an error of name not being defined
I think because it is inside a {} and you can’t just randomly access it
so it get stuck there

1 Like

if you use dot notation it is checking if there is a property with that exact name

to access properties using variables you need to use bracket notation

let me = {name: "alex", height: 180, weight: 90, x: "secret"};

let x = name;

console.log(me.x) // what should this print?
// we have a property name of "x",
// so it can't be that me.x and me.name are equal

//try also these:
console.log(me[name])
console.log(me["name"])
console.log(me[x]);
console.log(me["x"]);
1 Like