Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sometimes accessing object properties with dot notation returns undefined? [duplicate]

Tags:

javascript

This for-in loop I wrote is printing values of "undefined" for all of the object properties:

let user = {
  id: 1,
  name: "Some name"
};
for (let prop in user)
  console.log(prop + ": " + user.prop);

The console output:

id: undefined
name: undefined
like image 567
Ali Ataf Avatar asked Jan 18 '26 12:01

Ali Ataf


2 Answers

You can't use a variable to access an object property that way. It thinks you are trying to access a property called "prop". The way you use a variable to get an object property by name is like this:

let user = {
  id: 1,
  name: "Some name"
};
for (let prop in user)
  console.log(prop + ": " + user[prop]);
like image 62
anbcodes Avatar answered Jan 21 '26 03:01

anbcodes


user.prop is expecting an actual property named prop on the user object, something like this:

let user = {
  prop: 'not undefined'
  id: 1,
  name: "Some name"
};

I'm guessing you meant to use bracket notation to access properties?

let user = {
      id: 1,
      name: "Some name"
    };
for (let prop in user)
  console.log(prop + ": " + user[prop]);
like image 27
stealththeninja Avatar answered Jan 21 '26 04:01

stealththeninja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!