Basic Data Structures - 'for...in' exercise

In ‘JavaScript Algorithms and Data Structures’ in the ‘Basic Data Structures’ section, I have a question regarding the ‘for…in’ exercise.

This challenge was difficult, but thanks to the provided help, I was able to make it work and understand the code. However I am confused about how JavaScript sees ‘result++’ as the tested ‘value’ in the if/stmt. Does JavaScript assign the checked ‘value’ to any variable used in resulting if statements? Or is there something else happening?

Here is my code. Thank you in advance for your help.

let oneUser = {
  Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false }
}

function countOnline(usersObj) {
  let result = 0;
  for (let user in usersObj) {
    let value = usersObj[user].online;
  
    if (value === true) {
      result++;
    }
  }
  return result;
}
console.log(countOnline(oneUser));
1 Like

Hi I am a little confused by your question, could you elaborate more?

what is happening is exactly what’s written there

result starts at 0

then inside the function result is increased by one everything that usersObj[user].online is true (the user is online)

That’s exactly right you have got it. Result is a variable outside of the for in loop so each time it goes through the loop to checks if the value of user object online is true, if so it adds a value of 1 (result ++ is essentially a shorthand way of writing result = result +1. Then after all loops are complete the return value of result which is the number of users online. Hope that helps still not quite sure of the question though.

It wasn’t me with the question

Thank you @ilenia. That is very helpful.

@footballblubber, sorry for the confusion. I was basically not understanding how the ‘result’ variable got its value from the ‘value’ variable inside the for loop and if/stmt, since these are two separate variables.

But I think @ilenia helped me understand this. When the if/stmt finds a ‘true’ value, then ‘result’ is increased by 1 and that’s how result knows how many ‘true’ values there are. Hope I got that right. :slight_smile:

Thanks everyone for your help.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.