JavaScript property of a property

Why does this not work while using usersObj.x.online or even usersObj[x][online] instead of usersObj[x].online in the given below function ?

function countOnline(usersObj) {
 let num=0;
 for(let x in usersObj){
   if(usersObj[x].online===true){
     num++;
   }
 }
 return num;
}

Hi @vishveshpanchal101 !

Welcome to the forum!

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

usersObj does not have a property named x and dot notation can’t be used for variables

here online is an undefined variable, you would need to use usersObj[x]["online"]

2 Likes

Thank you for the support and formatting of the post.

Yes, I understood about the

usersObj

not having the property x but the second part where

online

undefined variable and need to use double quotes for it. Can I get some more explanation or any content to read?

when you use bracket notation, the content is evaluated. you can use usersObj[x] because x is a variable with a value. you do not have an online variable, so usersObj[x][online] is like usersObj[x][undefined]

2 Likes