JavaScript: Is a member defined?
Asked Answered
A

6

20

It seems to me that there are four different ways I can determine whether a given object (e.g. foo) has a given property (e.g. bar) defined:

  1. if (foo.hasOwnProperty(bar)) {
  2. if ('bar' in foo) {
  3. if (typeof foo.bar !== 'undefined') {
  4. if (foo.bar === undefined) {

To determine if there is a property named "bar" in the object foo, are all three of those statements equivalent? Are there any sublte semantics I don't know that makes any of these three statements different?

Auster answered 16/12, 2011 at 20:47 Comment(1)
Worth noting that, unless someone has overwritten the global undefined variable, 3 can also be done as if (foo.bar !== undefined) {.Mohsen
F
17

No they are totally different. Example:

foo = {bar: undefined};
Object.prototype.baz = undefined;
Object.prototype.bing = "hello";

Then:

(typeof foo.bar != "undefined")  === false
('bar' in foo)                   === true
(foo.hasOwnProperty('bar'))      === true


(typeof foo.baz != "undefined")  === false
('baz' in foo)                   === true
(foo.hasOwnProperty('baz'))      === false


(typeof foo.bing != "undefined") === true
('bing' in foo)                  === true
(foo.hasOwnProperty('bing'))     === false

Logic-wise:

  • foo.hasOwnProperty('bar') implies 'bar' in foo
  • typeof foo.bar != "undefined" implies 'bar' in foo
  • But those are the only inferences you can draw; no other implications are universally true, as the above counterexamples show.
Fasten answered 16/12, 2011 at 20:51 Comment(1)
+1 - I forgot to consider bar being on foo, but set to undefinedHypophysis
L
10

These are all different:

  1. foo.hasOwnProperty('bar') tells you whether foo has the property and does not perform lookup along the prototype chain.

  2. 'bar' in foo checks the prototype chain and returns true when it finds property bar in any object along the chain.

  3. typeof foo.bar != 'undefined' returns true if foo or any object along its prototype chain has property bar and it's value is not undefined.

Here is an example that demonstrates these differences:

var foo1 = { 'bar1': 10, 'bar2': undefined };
function ctor() {}
ctor.prototype = foo1;
var foo2 = new ctor();
foo2.bar3 = 20;

console.log(foo2.hasOwnProperty('bar1')); // false
console.log(foo2.hasOwnProperty('bar2')); // false
console.log(foo2.hasOwnProperty('bar3')); // true
console.log(foo2.hasOwnProperty('bar4')); // false

console.log('bar1' in foo2); // true
console.log('bar2' in foo2); // true
console.log('bar3' in foo2); // true
console.log('bar4' in foo2); // false

console.log(typeof foo2.bar1 != 'undefined'); // true
console.log(typeof foo2.bar2 != 'undefined'); // false
console.log(typeof foo2.bar3 != 'undefined'); // true
console.log(typeof foo2.bar4 != 'undefined'); // false
Lobotomy answered 16/12, 2011 at 20:52 Comment(0)
B
2

one difference is that, method 1 will check only foo object for property bar while the last two methods will also check the prototype for inherited property.

Blayze answered 16/12, 2011 at 20:50 Comment(0)
H
2
'bar' in foo 

will look anywhere up the prototype chain. Testing to see if foo.bar !== undefined will also return true if bar is anywhere in foo's prototype chain, but remember if bar is defined on foo, and set to undefined, this will return false.

hasOwnProperty is more choosy - it will only return true is bar is defined as a direct property of foo.

Per MDN

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

Hypophysis answered 16/12, 2011 at 20:51 Comment(0)
S
2

There are indeed some subtle differences between the various methods/keywords.

  1. foo.hasOwnProperty('bar') returns true only if the property 'bar' is defined on the foo object itself. Other properties, such as 'toString' will return false however since they are defined up the prototype chain.

  2. The in keyword operator returns true if the specified property is in the specified object. Both 'bar' in foo and 'toString' in foo would return true.

  3. Since you are checking for the state of the property, the result will be true when bar is not defined on foo and when bar is defined but the value is set to undefined.

Sommer answered 16/12, 2011 at 20:56 Comment(0)
I
0

To add to what others have said, if you just want to know if a property exists and has a non-falsey value (not undefined, null, false, 0, "", NaN, etc...), you can just do this:

if (foo.bar) {
     // code here
}

As long as falsey values are not interesting to you for your particular circumstance, this shortcut will tell you if the variable has been set to something useful for you or not.

If you want to know if the property exists on the object in any way, I find this the most useful, brief and readable:

if ('bar' in foo) {
    // code here
}

One can also use something similar on function arguments (again as long as a falsey value isn't something you care about):

function foo(bar) {
    if (bar) {
        // bar was passed and has some non-falsey value
    }
}
Irresolution answered 16/12, 2011 at 21:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.