Created
June 14, 2016 23:52
-
-
Save fernandocanizo/0f386ae1c9dea512d010012d3de80956 to your computer and use it in GitHub Desktop.
Ways to check for an object property
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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