Last active
December 7, 2024 05:36
-
-
Save devudit/d9298b5bb3211a622fb00054f1a862b0 to your computer and use it in GitHub Desktop.
JavaScript isset() equivalent
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
// I generally use the typeof operator: | |
if (typeof obj.foo !== 'undefined') { | |
// your code here | |
} | |
// It will return "undefined" either if the property doesn't exist or its value is undefined. | |
// There are other ways to figure out if a property exists on an object, like the hasOwnProperty method: | |
if (obj.hasOwnProperty('foo')) { | |
// your code here | |
} | |
// And the in operator: | |
if ('foo' in obj) { | |
// your code here | |
} | |
// The difference between the last two is that the hasOwnProperty method will check if | |
// the property exist physically on the object (the property is not inherited). | |
// The in operator will check on all the properties reachable up in the prototype chain, e.g.: | |
var obj = { foo: 'bar'}; | |
obj.hasOwnProperty('foo'); // true | |
obj.hasOwnProperty('toString'); // false | |
'toString' in obj; // true | |
// As you can see, hasOwnProperty returns false and the in operator returns true when checking the toString | |
// method, this method is defined up in the prototype chain, because obj inherits form Object.prototype. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks