Skip to content

Instantly share code, notes, and snippets.

@devudit
Last active February 8, 2024 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devudit/d9298b5bb3211a622fb00054f1a862b0 to your computer and use it in GitHub Desktop.
Save devudit/d9298b5bb3211a622fb00054f1a862b0 to your computer and use it in GitHub Desktop.
JavaScript isset() equivalent
// 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.
@7526943851amit
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment