Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fernandocanizo/0f386ae1c9dea512d010012d3de80956 to your computer and use it in GitHub Desktop.
Save fernandocanizo/0f386ae1c9dea512d010012d3de80956 to your computer and use it in GitHub Desktop.
Ways to check for an object property
"use strict";
// There are three ways to check if an object has a property:
const obj = {
one: 1
};
const otherObj = Object.create(obj);
// 1. !! (bang-bang)
// DON'T USE IT, it coerces your value and can give false negatives
!!obj['one']; // true
!!obj['two']; // false
!!otherObj['one']; // true
!!otherObj['two']; // false
// So far so good, but...
obj.one = false;
!!obj['one']; // false
// 2. hasOwnProperty method
// This is the recommended way
obj.hasOwnProperty('one'); // true
obj.hasOwnProperty('two'); // false
// But hasOwnProperty, as its name indicates, doesn't check the prototype chain
otherObj.hasOwnProperty('one'); // false
// 3. Using `in`
('one' in obj); // true
('two' in obj); // false
('one' in other); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment