(The result is always true)Check if an Object has a Property

Tell us what’s happening:

Your 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) {
  // change code below this line
  let names = ["Alan","Jeff","Sarah","Ryan"];
  for (let i=0 ; i<names.length ; i++){
    if (names[i] in obj){
      return true;
    }
    return false;
  };
  // change code above this line
}*/

function isEveryoneHere(obj) {
  // change code below this line
  let names = ["Alan","Jeff","Sarah","Ryan"];
  for (let i=0 ; i<names.length ; i++){
    return names[i] in obj;
     };
  // change code above this line
}
console.log(isEveryoneHere(users));

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/check-if-an-object-has-a-property

These two codes passed the challenge.
I tried to test it on repl.it but the result is always true even I changed the property name.
I think it’s because the return , which stop the code once it encounters the first true.
But how can I write it in order to return false if there is no matched property and the whole code will still keep going?

1 Like

Good question. And you’re absolutely right when you say this:

I think it’s because the return , which stop the code once it encounters the first true.

Right now, your function should be named isTheFirstPersonHere(), rather than isEveryoneHere() because whether it returns true or not depends completely on the first name in your names array!

To fix this, try changing what your for loop does. In the for loop, just check each name, and for each name, if it is NOT in obj, then return false.

If any of the names is missing, then the function will return false and for loop will never complete.

But if all the names are there, the for loop will complete successfully without having caused the function to return anything. At that point we can be sure that every name is in obj, so we can return true. But that return statement needs to come after the for loop.

Try to implement that logic and see if that works for you. Good luck!

[P.S. Thanks for including your own guess about what was wrong with your code. That lets me and others know that you’ve done some work trying to reason about the code you’ve written. Not everybody who asks questions on here does that, but it’s a really good habit to have, so kudos!]

1 Like

Thank you very much! I tried what you said and it worked! :wink:

Great! Glad to hear it. Good luck going forward.

function isEveryoneHere(obj) {
// change code below this line
return (users.hasOwnProperty(‘Alan’,“Jeff”,“Sarah”,‘Ryan’))

// change code above this line
}