Detecting an undefined object property

1,368,193

Solution 1

I believe there are a number of incorrect answers to this topic. Contrary to common belief, "undefined" is not a keyword in JavaScript and can in fact have a value assigned to it.

Correct Code

The most robust way to perform this test is:

if (typeof myVar === "undefined")

This will always return the correct result, and even handles the situation where myVar is not declared.

Degenerate code. DO NOT USE.

var undefined = false;  // Shockingly, this is completely legal!
if (myVar === undefined) {
    alert("You have been misled. Run away!");
}

Additionally, myVar === undefined will raise an error in the situation where myVar is undeclared.

Solution 2

Despite being vehemently recommended by many other answers here, typeof is a bad choice. It should never be used for checking whether variables have the value undefined, because it acts as a combined check for the value undefined and for whether a variable exists. In the vast majority of cases, you know when a variable exists, and typeof will just introduce the potential for a silent failure if you make a typo in the variable name or in the string literal 'undefined'.

var snapshot = …;

if (typeof snaposhot === 'undefined') {
    //         ^
    // misspelled¹ – this will never run, but it won’t throw an error!
}
var foo = …;

if (typeof foo === 'undefned') {
    //                   ^
    // misspelled – this will never run, but it won’t throw an error!
}

So unless you’re doing feature detection², where there’s uncertainty whether a given name will be in scope (like checking typeof module !== 'undefined' as a step in code specific to a CommonJS environment), typeof is a harmful choice when used on a variable, and the correct option is to compare the value directly:

var foo = …;

if (foo === undefined) {
    ⋮
}

Some common misconceptions about this include:

  • that reading an “uninitialized” variable (var foo) or parameter (function bar(foo) { … }, called as bar()) will fail. This is simply not true – variables without explicit initialization and parameters that weren’t given values always become undefined, and are always in scope.

  • that undefined can be overwritten. It’s true that undefined isn’t a keyword, but it is read-only and non-configurable. There are other built-ins you probably don’t avoid despite their non-keyword status (Object, Math, NaN…) and practical code usually isn’t written in an actively malicious environment, so this isn’t a good reason to be worried about undefined. (But if you are writing a code generator, feel free to use void 0.)

With how variables work out of the way, it’s time to address the actual question: object properties. There is no reason to ever use typeof for object properties. The earlier exception regarding feature detection doesn’t apply here – typeof only has special behaviour on variables, and expressions that reference object properties are not variables.

This:

if (typeof foo.bar === 'undefined') {
    ⋮
}

is always exactly equivalent to this³:

if (foo.bar === undefined) {
    ⋮
}

and taking into account the advice above, to avoid confusing readers as to why you’re using typeof, because it makes the most sense to use === to check for equality, because it could be refactored to checking a variable’s value later, and because it just plain looks better, you should always use === undefined³ here as well.

Something else to consider when it comes to object properties is whether you really want to check for undefined at all. A given property name can be absent on an object (producing the value undefined when read), present on the object itself with the value undefined, present on the object’s prototype with the value undefined, or present on either of those with a non-undefined value. 'key' in obj will tell you whether a key is anywhere on an object’s prototype chain, and Object.prototype.hasOwnProperty.call(obj, 'key') will tell you whether it’s directly on the object. I won’t go into detail in this answer about prototypes and using objects as string-keyed maps, though, because it’s mostly intended to counter all the bad advice in other answers irrespective of the possible interpretations of the original question. Read up on object prototypes on MDN for more!

¹ unusual choice of example variable name? this is real dead code from the NoScript extension for Firefox.
² don’t assume that not knowing what’s in scope is okay in general, though. bonus vulnerability caused by abuse of dynamic scope: Project Zero 1225
³ once again assuming an ES5+ environment and that undefined refers to the undefined property of the global object.

Solution 3

In JavaScript there is null and there is undefined. They have different meanings.

  • undefined means that the variable value has not been defined; it is not known what the value is.
  • null means that the variable value is defined and set to null (has no value).

Marijn Haverbeke states, in his free, online book "Eloquent JavaScript" (emphasis mine):

There is also a similar value, null, whose meaning is 'this value is defined, but it does not have a value'. The difference in meaning between undefined and null is mostly academic, and usually not very interesting. In practical programs, it is often necessary to check whether something 'has a value'. In these cases, the expression something == undefined may be used, because, even though they are not exactly the same value, null == undefined will produce true.

So, I guess the best way to check if something was undefined would be:

if (something == undefined)

Object properties should work the same way.

var person = {
    name: "John",
    age: 28,
    sex: "male"
};

alert(person.name); // "John"
alert(person.fakeVariable); // undefined

Solution 4

What does this mean: "undefined object property"?

Actually it can mean two quite different things! First, it can mean the property that has never been defined in the object and, second, it can mean the property that has an undefined value. Let's look at this code:

var o = { a: undefined }

Is o.a undefined? Yes! Its value is undefined. Is o.b undefined? Sure! There is no property 'b' at all! OK, see now how different approaches behave in both situations:

typeof o.a == 'undefined' // true
typeof o.b == 'undefined' // true
o.a === undefined // true
o.b === undefined // true
'a' in o // true
'b' in o // false

We can clearly see that typeof obj.prop == 'undefined' and obj.prop === undefined are equivalent, and they do not distinguish those different situations. And 'prop' in obj can detect the situation when a property hasn't been defined at all and doesn't pay attention to the property value which may be undefined.

So what to do?

1) You want to know if a property is undefined by either the first or second meaning (the most typical situation).

obj.prop === undefined // IMHO, see "final fight" below

2) You want to just know if object has some property and don't care about its value.

'prop' in obj

Notes:

  • You can't check an object and its property at the same time. For example, this x.a === undefined or this typeof x.a == 'undefined' raises ReferenceError: x is not defined if x is not defined.
  • Variable undefined is a global variable (so actually it is window.undefined in browsers). It has been supported since ECMAScript 1st Edition and since ECMAScript 5 it is read only. So in modern browsers it can't be redefined to true as many authors love to frighten us with, but this is still a true for older browsers.

Final fight: obj.prop === undefined vs typeof obj.prop == 'undefined'

Pluses of obj.prop === undefined:

  • It's a bit shorter and looks a bit prettier
  • The JavaScript engine will give you an error if you have misspelled undefined

Minuses of obj.prop === undefined:

  • undefined can be overridden in old browsers

Pluses of typeof obj.prop == 'undefined':

  • It is really universal! It works in new and old browsers.

Minuses of typeof obj.prop == 'undefined':

  • 'undefned' (misspelled) here is just a string constant, so the JavaScript engine can't help you if you have misspelled it like I just did.

Update (for server-side JavaScript):

Node.js supports the global variable undefined as global.undefined (it can also be used without the 'global' prefix). I don't know about other implementations of server-side JavaScript.

Solution 5

The issue boils down to three cases:

  1. The object has the property and its value is not undefined.
  2. The object has the property and its value is undefined.
  3. The object does not have the property.

This tells us something I consider important:

There is a difference between an undefined member and a defined member with an undefined value.

But unhappily typeof obj.foo does not tell us which of the three cases we have. However we can combine this with "foo" in obj to distinguish the cases.

                               |  typeof obj.x === 'undefined' | !("x" in obj)
1.                     { x:1 } |  false                        | false
2.    { x : (function(){})() } |  true                         | false
3.                          {} |  true                         | true

Its worth noting that these tests are the same for null entries too

                               |  typeof obj.x === 'undefined' | !("x" in obj)
                    { x:null } |  false                        | false

I'd argue that in some cases it makes more sense (and is clearer) to check whether the property is there, than checking whether it is undefined, and the only case where this check will be different is case 2, the rare case of an actual entry in the object with an undefined value.

For example: I've just been refactoring a bunch of code that had a bunch of checks whether an object had a given property.

if( typeof blob.x != 'undefined' ) {  fn(blob.x); }

Which was clearer when written without a check for undefined.

if( "x" in blob ) { fn(blob.x); }

But as has been mentioned these are not exactly the same (but are more than good enough for my needs).

Share:
1,368,193
Matt Sheppard
Author by

Matt Sheppard

Software engineer in Canberra, Australia

Updated on February 17, 2022

Comments

  • Matt Sheppard
    Matt Sheppard over 2 years

    What's the best way of checking if an object property in JavaScript is undefined?