Check if an Object has a Property - JavaScript Data Structures

I was able to solve this challenge using a for loop. The two posted solutions utilize && operators and the every method though.

Just wondering from an efficiency point of view, if my solution is less than ideal compared to the posted solutions?

My Solution:

function isEveryoneHere(userObj) {
let arr = ['Alan', 'Jeff', 'Sarah', 'Ryan'];
  for (let i = 0; i < arr.length; i++) {
    if (userObj.hasOwnProperty(arr[i]) == false) {
      return false;
    }  
  } return true;
} 
2 Likes

We have blurred this solution (with [spoiler][/spoiler] tags) so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.

1 Like

How is it possible without if? I played around with @devonhughes’s code and tried to figure out how to make it with for loop only.

function isEveryoneHere(userObj) {
let arr = ['Alan', 'Jeff', 'Sarah', 'Ryan'];
  for (let i = 0; i < arr.length; i++) {
    return arr[i] in userObj;
  }
}  

It returns false only on Alan not being among object properties. On other names it returns true. Same story with hasOwnProp.

1 Like

The comment was invalid. Ignore it.

1 Like

here’s my solution to this. Not the most elegant but it works :slight_smile:

function isEveryoneHere(userObj) {
  // Only change code below this line
  let user = ['Alan', 'Jeff', 'Sarah', 'Ryan']
  let check = 0;

  for (let i = 0; i < user.length; i++)
    if(user[i] in userObj == false) {
      check = 1;
    }

    return check <= 0

}

I used a for loop as well. Not the best solution but it works fine.

function isEveryoneHere(userObj) {
  let names = ['Alan', 'Jeff', 'Sarah', 'Ryan'];
  let result = '';
  for (let i = 0; i < names.length; i++) {
    if (userObj.hasOwnProperty(names[i])) {
      result = true;
    } else {
      result = false;
      return result;
    }
  } 
  return result; 
}