Better solution for 'Check if an Object has a Property'

Tell us what’s happening:
Is there any better solution to this challenge?
I think I have over-complicated it.

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

console.log(isEveryoneHere(users));

Challenge: Check if an Object has a Property

Link to the challenge:

You could avoid result variable, by using early return:

const names = ['Alan', 'Jeff', 'Sarah', 'Ryan']
for (let i = 0; i < names.length; i++) {
  if (!obj.hasOwnProperty(names[i])) return false;
}
return true

Alternative:

const names = ['Alan', 'Jeff', 'Sarah', 'Ryan']
return names.every(name => obj[name])
1 Like