I have a problem with Iterate Through the Keys of an Object with a for…in Statement | challenge.
First, this is 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
// Create var called 'i' to start count online users from 0
let i = 0;
// use for to display all key for any obj come from function argument
for (let user in obj) {
// small condition to compare online key with his content
if(obj[user]['online'] == true) {
return i++
}
}
// change code above this line
}
console.log(countOnline(users));
I tried to explain my answer in the comments above and give you some information about how i think of it but, it’s return 0 ? and i don’t know why ??
A return statement stops function execution and returns whatever the expression to its right evaluates to. That’s what happens inside your for loop right now, the first time it encounters a user who is online.
The for in loop is accessed only one time, at the end of the first and only iteration the return statement breaks the function and returns the value of i before the ++ operator changes the value of i.
Your for loop should be operating on the i variable and not return (you should be returning after the loop is over instead). You also reference obj[users] which doesn’t exist
Edit: for some reason I missed the obj being referenced as an argument to the function
So, to clarify, I said your for loop (i.e. your for...in... loop) should be operating on the i variable, not to use it as a traditional for loop i. For example (minor spoilers ahead if you still want to try it on your own without any structural guidance):
const obj = {a: 'hey'}
function myFunc() {
let i = 0
for (let key in obj) {
//increment the i variable, but don't return in here.
//returning in here will return the entire function, not "break" the for loop
}
//return the i variable when you've achieved what needs to happen in the for loop
}
you are right, you are doing really well, it is just that the return statement will stop the function and return the value, so if you put it inside a loop, the loop doesn’t do what you want. and if you use i++, that is enough to change the value of i, there it is not necessary to use return there
the return statement is necessary, just somewhere else
@huntinghawk1415@ILM
OH, Finally!! i understand what was happened here
I thought i’m very stupid
well, it’s really greet help and it’ll help me later to understand what really return sequence can do !!
So, THANK YOU AGAIN and sorry if you tried with my
Very stupid !? Not for sure! The aha moment is sign of intelligence You kept reading, trying and asking according to the information everyone was giving you. Now you have understanding of for…in iterator, i++ operator and return statement. What an adventure.