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
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]);
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With