1

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,040
  • 6
  • 32
  • 55
Ali Ataf
  • 266
  • 3
  • 12
  • 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

4

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
  • 799
  • 5
  • 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,179
  • 1
  • 21
  • 39