3

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
Eddie
  • 26,593
  • 6
  • 36
  • 58
Ali Ataf
  • 391
  • 3
  • 13
  • 1
    `user.prop` always returns the value of key with the name "prop" - and has nothing to do with the variable named "prop" - use `[]` notation, i.e. `user[prop]` – Jaromanda X Jul 27 '19 at 01:37

2 Answers2

5

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]);
anbcodes
  • 849
  • 6
  • 15
1

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]);
stealththeninja
  • 3,576
  • 1
  • 26
  • 44