How to return the amount of true/false?

Challenge asks:
return the number of users whose online property is set to true.
I know how to return but this return wants me to count boolean values of an object within an object multiple times and return a value? Do I convert true to a number and return that number? How do I convert the amount of true’s to a number?


function countOnline(usersObj) {
// Only change code below this line
for (let user in usersObj) {
if (usersObj[user].online===true) {
  return 
}
}
// Only change code above this line
} 



Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36.

Challenge: Iterate Through the Keys of an Object with a for…in Statement

Link to the challenge:

it’s just like counting apples
start with apples=0
then each time you encounter
the boolean true value
add another apple

then return your apples

So I need to use another for loop then use a return in that loop?

No
the return should be the last line
in any function
even though it is often
found in other place
sometimes even in multiple
places . Good Practice Demands
only one return only on the last line
at the top of your code set apple to zero
each time in the loop that the condition
is true add 1 to apple
this will result in the same number
in apple as there are users online
in the last line return apple;

So I tried putting let apple=0; in the loop and the if statement and then I just put in in the top of the function to see how the scopes would work. None of it is working

function countOnline(usersObj) {
  // Only change code below this line
  let apple=0;
for (let user in usersObj) {
  if (usersObj[user].online===true) {
  apple + 1;
  return apple;

    
  }
}

You want to increment the apple variable, but the expression you’re using isn’t getting it done. You’re close!

2 Likes

Also, keep in mind that as soon as you return from a function, you stop doing anything in that function, to include counting.

1 Like

I changed it to apple++, because plus one just adds 1 instead of incrementing with the loop I guess? It passed btw! Thank you!

1 Like

I moved the return outside the loop, and it passed with Cactus’s advice as well. Thank you!