Basic Data Structures: Iterate Through the Keys of an Object with a for...in Statement #2

Tell us what’s happening:
Solution looks correct, is nearly identical to solution offered in ‘Get a Hint’ thread, but does not pass tests. Using console.log() to print out test results reveals:
0
0
1

These results don’t make sense to me, given the coded

Your code so far


function countOnline(usersObj) {
// Only change code below this line
let i =  0; {
  for (let users in usersObj) {
    if (usersObj[users][online] === true)
    console.log(i++);
}
}
// Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0.

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

Link to the challenge:

Your code has two issues:

First, in order to use bracket notation, online must be a string or a variable holding a string.

Second, you are not returning a quantity, but the test expects you to return the value of i.

1 Like

this yields same results:

function countOnline(usersObj) {

  // Only change code below this line

  let i = 0; 

    for (let users in usersObj) {

      if (usersObj[users].online === true)

      return i++;

  }

It doesn’t yield exactly the same results.

As soon as your code encounters a return, execution of your function stops. You have a return inside of your loop, so your loop will only run once.

1 Like

Still yields same results (0, 0, 1), correct sequence of answers being (1, 2, 0).

function countOnline(usersObj) {

  // Only change code below this line

  let i = 0; 

    for (let users in usersObj) {

      if (usersObj[users].online === true)

      i++;

  }

  

  // Only change code above this line

}

Now you have completely removed the return.

The instructions require you to return your value stored in i, but you cannot return inside of the for loop.


I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

Thanks for your help Jeremy

1 Like

Still not getting it, but tinkering

So essentially, it asks you number of users. So just create a variable that increments whenever the online property is true, and then return that.

You’re mostly there, you just need to put your return inside your function but after you have finished counting.

Sorry if I’m giving you just little nudges. You’re so close that I’m trying to nudge you without giving you the answer so you can have that ‘ah-ha’ moment!

Oh definitely much better that way