Alternate solution for "Check if an Object has a Property" fails

Tell us what’s happening:
I think I have found a valid solution for the challenge “Check if an Object has a Property”, but the tests fail. Could someone comment if my solution is wrong and why or if the tests didn’t evaluate my solution correctly?
My code so far


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

function isEveryoneHere(obj) {
// Only change code below this line
for (let name in obj) {
  if (!(name in users)) {
    console.log(name + " is false.")
    return false;
  } else {
    console.log(name + " is true.")
    }
}
return true;
// Only change code above this line
}

console.log(isEveryoneHere(users));

(I have added some console.log statements to check if I got the correct branch of the if statement.

  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Safari/537.36.

Challenge: Check if an Object has a Property

Link to the challenge:

As I understand it, your code checks if every name in the obj is also in users, but it does not check that every name in users is present in obj.

Thank you for the really fast answer :heavy_heart_exclamation:

Maybe I am confusing something: But if I change the two lines from

for (let name in users) {
    if (!(name in obj)) {

to

for (let name in obj) {
    if (!(name in users)) {

I got the same result: All the tests fail.

I will rephrase my question: Is there also a solution with a “For-in” loop? If so: why do the tests with my program code fail?

I think I see what’s going on. The tests modify the user object, so you cannot use the contents of that global variable in your function. - In general it’s dicey relying upon global variables in your logic anyways.

Aha!! This explains why the tests fail. And: Yes, it is not a good style to rely upon global variables! Thank you so much for your help!

1 Like

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