Iterate Through the Keys of an Object with a for...in Statement, deeper explanation

Tell us what’s happening:
Can anyone explain me why it gives different result when I return the user variable inside the function instead of console log the user.

Your code so far


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 obj) {
    console.log(user)
  }
  // change code above this line
}

countOnline(users);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/-iterate-through-the-keys-of-an-object-with-a-for---in-statement

A return only happens once, and the the function execution ends. If you put a return inside your for loop, only the first user will ever be looked at.

1 Like