Is there a way to solve this with less code?

Hey, I initially tried solving this with the code in the bottom of this post but it wouldn’t work.

It seems odd that I’d need to rewrite each like this

if ("Alan" in users &&
    "Jeff" in users &&
    "Sarah" in users &&
    "Ryan" in users)
  {
    return true;
  }
  return false;`

or this

if (
    obj.hasOwnProperty("Alan") &&
    obj.hasOwnProperty("Jeff") &&
    obj.hasOwnProperty("Sarah") &&
    obj.hasOwnProperty("Ryan")
  ) {
    return true;
  }
  return false; `

Is there a way to generally not have to re write obj.hasOwnProperty or in users ? Thanks

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) {
// Only change code below this line
if ('Alan' && 'Jeff' && 'Sarah' && 'Ryan' in users) {
  return true;
} else {
  return false;
  }
// Only change code above this line
}

console.log(isEveryoneHere(users)); 

Challenge: Check if an Object has a Property

Link to the challenge:

Hi @am93 . You can try out the following as well

return ['Alan', 'Jeff', 'Sarah', 'Ryan'].every(user => obj[user])

EDIT.
Thanks @ieahleen for pointing this out. Like it has been explained by @ieahleen below, the solution I have provided above only works if none of the properties you are checking for has a falsy value. So your safest option is to use obj.hasOwnProperty

return ['Alan', 'Jeff', 'Sarah', 'Ryan'].every(user => obj.hasOwnProperty(user))

that would not work if the properties have falsy values so hasOwnProperty would still be needed

every was my idea too

1 Like

Thanks. Don’t think every has been covered yet for me.

I thought if ('Alan' && 'Jeff' && 'Sarah' && 'Ryan' in users) could’ve worked. Can you explain why it does not?

I believe it is because 'Alan' && 'Jeff' && 'Sarah' && 'Ryan' in users will evaluate to 'true' && 'true' && 'true' && 'true if Ryan is a property in users. Essentially you are not checking whether Alan, Jeff and Sarah are properties of user object but you are checking whether they are truthy values as a result they will evaluate to true. The only property you are checking is Ryan from 'Ryan' in users.

The JS engine interprets your code as

if ('Alan' && 'Jeff' && 'Sarah' && ('Ryan' in users))

I hope that helps.

1 Like

Yup that helps, thank you!