DEV Community

loading...

Checking if an Object has a Property

rthefounding profile image Randy Rivera ・1 min read
  • Now we can add, modify, and remove keys from objects. But what if we just wanted to know if an object has a specific property? One way of doing so used the hasOwnProperty() method.
  • We've created an object, users, with some users in it and a function isEveryoneHere, which we pass the users object to as an argument. Finish writing this function so that it returns true only if the users object contains all four names, Alan, Jeff, Sarah, and Ryan, as keys, and false otherwise.
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

  // Only change code above this line
}

console.log(isEveryoneHere(users));
Enter fullscreen mode Exit fullscreen mode
  • Answer:
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) {
if (
  users.hasOwnProperty("Alan") &&
  users.hasOwnProperty("Jeff") &&
  users.hasOwnProperty("Sarah") &&
  users.hasOwnProperty("Ryan")
) {
  return true;
} else {
  return false;
}
}
Enter fullscreen mode Exit fullscreen mode
console.log(isEveryoneHere(users)); //console will display true
Enter fullscreen mode Exit fullscreen mode
  • Checks whether object contains all users by using the hasOwnProperty method for each name with the && operator to return a true or false value.

Discussion (1)

Collapse
pawelmiczka profile image
Paweł Miczka

There are some downside using hasOwnProperty and it can be replaced with simple users.Alan !== undefined

Forem Open with the Forem app