Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active May 29, 2016 20:00
Show Gist options
  • Save dfkaye/4d29d80cf119d27bd189f7771731133a to your computer and use it in GitHub Desktop.
Save dfkaye/4d29d80cf119d27bd189f7771731133a to your computer and use it in GitHub Desktop.
object property accesses, response to tip#3 in https://gist.github.com/yuval-a/d5794cc1439c08af085f
// response to https://gist.github.com/yuval-a/d5794cc1439c08af085f
// via linkedin post https://www.linkedin.com/groups/121615/121615-6135714090246553602
// specifically tip #3,
// property === undefined is faster than hasOwnProperty(property)
// I'm not sure what the intent is, because the two checks compare different things...
var a = { name: 'aaaaaa' };
a.name === undefined // false (expected)
a.hasOwnProperty('name') // true (expected)
// ...because inheritance via the prototype chain is the whole reason for `hasOwnProperty`
// in the first place:
var b = Object.create(a);
b.name === undefined // false (expected)
b.hasOwnProperty('name') // false (oh...)
// So, if you're only checking the _existence_ of the property, use the ('property' in object)
// expression, _if_ existence is all you're checking:
'name' in a // true
// Otherwise if you're checking whether the _value_ of the property is undefined or null,
// but not any other falsey value (0, false, NaN or the empty string ('')), then use the looser
// equality operator, `==`.
// Here's a test object with some one-liner assertions below to show all this:
var test = {
name: 'test name',
n: null,
u: undefined,
x: !!0,
y: '',
z: 0
};
// Existence checks are not value checks. If a key exists its _value_
// can still be undefined
'bonk' in test // false (expected)
test.hasOwnProperty('bonk') // false (expected)
// These evaluate to true because the key 'u' exists on the test object
'u' in test // true
test.hasOwnProperty('u') // true
// check their values, or rather what their keys resolve to...
test.bonk == null // true
test.n == null // true
test.u == null // true
// whereas...
test.x == null // false
test.y == null // false
test.z == null // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment