0

Can someone explain to me why the notation on this code works, but the others do not.

This is the code that works (it logs the booleans of the users online status).

function countOnline(usersObj) {
for (let user in usersObj) {
    console.log(usersObj[user].online)
    }
}

countOnline({ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } })

Yet with the dot notation

for (let user in usersObj) {
    console.log(usersObj.user.online)
}

or even the bracket notation

for (let user in usersObj) {
    console.log(usersObj[user][online])
}

it doesn't work, I get the error "TypeError: Cannot read property 'online' of undefined". Would just like a bit more insight on this, as a newbie.

  • 1
    `user` is a variable, which is why you use brackets for it. `online` is not a variable, it's the actual key, so you use dot notation. You _could_ use bracket notation but would need to put it in quotes: `usersObj[user]["online"]` – Nick Jul 04 '21 at 18:23

0 Answers0