How does for...in works?

Can someone explain how the code logs each different key in the object? I understand the for loop that once the code is executed once, it repeats.

But how exactly does the bob variable replace the actual property names in the object such as
'Ryan' in users

Also, how does the for loop know when to end? Does it simply iterate through all keys?

  **Your code so far**

function countOnline(usersObj) 
{
for (let bob in users)
  {
  console.log(bob);
  }
}

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

console.log(countOnline(users))
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36 Edg/96.0.1054.53

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

Link to the challenge:

The developers of javascript created this syntax:

for (thisKey in thisObject){
// ....code...
}

thisKey and thisObject are to be replaced for your particular code data.

The javascript engine will then loop over the object and each time picks a new key . The awesome thing is you can get the keys from the object.

For example

const numbers = {'1':1, '2':2};
for (number in numbers){
console.log(`key is the number ${number}`, typeof(number))
}

for (let key in obj) is shorthand for

for (let i = 0; i < Object.keys(obj).length; i++) {
    let key = Object.keys(obj)[i];
}
1 Like

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