Solution Only Works if I Change the Object

Tell us what’s happening:
I only pass the test if all three users in the sample object are offline. If any one of them has their online status as true, then I won’t pass. I’m very confused because changing the users’ status in the provided object shouldn’t affect whether the function works or not.

  **Your code so far**

const users = {
Alan: {
  online: false
},
Jeff: {
  online: false
},
Sarah: {
  online: false
}
}

let count = 0

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

countOnline(users);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.3 Safari/605.1.15

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

Link to the challenge:

Why is this floating out here in the global space! You shouldn’t create global variables that didn’t already exist in these challenges.


Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2
2 Likes

By function, do you mean the for loop? Doesn’t the function only run once?

The tests run your function multiple times.

In general, a function isn’t really a function if you can only run it once.

3 Likes

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