Syntax to access object properties

Please see the following code:

let foo = {
bar: {
a: 5
}
};

alert(foo.bar); //I get [object Object]

for (i in foo) {
alert(foo.i); //I get undefined
};

Could someone explain why? Where does the difference lie there?

Your access to the object is invalid. Try:

for (i in foo) {
alert(i); //
};

Rather, perhaps (as you’re trying to iterate over foo.bar, try:

for (i in foo.bar) {
alert(i); //
};
1 Like