How is user defined? Iterate Through Keys of Object Category,

How is user defined? Iterate Through Keys of Object Category,
0

#1

In this challenge how are we defining the variable ?

I understand we are using `for (let user in users)’ to define the variable technically. But how does the code know that “user” is Alan, Jeff, Sarah, and Ryan specifically? Is it because that is the only property in the first level object? Thanks for any help!


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
  var counter = 0;
    for (var user in obj) {
        if (obj[user]["online"] === true) {
            counter++
        }
        // change code above this line

    } return counter;
}

  // change code above this line


console.log(countOnline(users));


#2

The for(…in…) syntax defines the user variable, and assigns it to each member of the users array in turn.

The array contains only objects as its first-level elements, as you’ve noted. The for(…in…) syntax would iterate over every member of that users array, and if one was, for example, a string, it would likely throw an error.

The fact that the users array is defined to a set format is what allows us to set each object, in turn, into the user variable.


#3

Thank you for taking the time to answer. That’s a great explanation.


#4

Glad I could help. It’s an easy gotcha, as it doesn’t seem intuitive to define a variable inline like that (though you see the same in the more common for(let i=0; ...) type loops). Good question, got me thinking too. :wink: