Why this simple for loop doesn´t work?

This is from the challenge: Basic Data Structures: Iterate Through the Keys of an Object with a for…in Statement

Objetive: " We’ve defined a function, countOnline ; use a for…in statement within this function to loop through the users in the users object and return the number of users whose online property is set to true ."

My code:

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function countOnline(obj) {
  // change code below this line
  for (let user in users) {
    let counter = 0
    if (obj[user].online){
      counter +=1
    }
    return counter;
  };
  // change code above this line
}

console.log(countOnline(users));

The problem is I don´t understand exactly where I have to put the counter variable in order to the counter not to reset to cero. I have tried putting it inside the if but then the counter gives 1.
The counter should give two. I have tried with console log and the for loop works correctly since it gives true and true for Jeff and Ryan and false to the rest like the challenge asks, but something as simple as convert that be counted I´m not able to. :frowning:

You have two problems, and they both have to do with where you have statements located. First, every time you go through the loop, you are setting counter to 0. You need to move this before the loop, so it only runs once. The second is where return counter; is located: you are returning the counter the very first time through the loop. You need to move it to after the loop, when the loop is finished.

1 Like

You have a couple of issues here, first you are saying counter = 0 inside the loop, that means that st every iteration of the loop the variable is set again to 0
And you have a return statement inside the loop, and when a return statement is executed the function is exited, as such your loop will never reach following iterations

You may want to move a few things around

1 Like

Damn, I had already tried that too but because of my confusion with the brackets I thought I had put the counter outside the loop when it fact i hadn´t! Well, its solved now, thanks for the fast reply bro