4

What is better?

if (obj === undefined) { }

vs.

if (typeof(obj) === 'undefined') { }
Alon Gubkin
  • 56,458
  • 54
  • 195
  • 288
  • 5
    The question was related to Performance, and all answers are about the better one regardless of performance –  Mar 11 '15 at 23:57

3 Answers3

5

If you somehow can't refrain from shadowing the global undefined, or can't keep from trying to reference undeclared variables, then use:

typeof x === 'undefined'

If you adhere to good coding practices, and believe in letting broken code break, use:

x === undefined

If you want a different alternative, you can use:

x === void 0;

...where void always returns undefined, and doesn't rely on the global property.

Another safeguard you can use is to use shadowing in a good way by defining a proper undefined in a function:

(function( undefined ) {

    // notice that no arguments were passed, 
    // so the `undefined` parameter will be `undefined`

    var x; 

    if( x === undefined ) {

    }

})();

...some people prefer to give it a different name:

(function( undef ) {

    // notice that no arguments were passed, 
    // so the `undefined` parameter will be `undefined`

    var x; 

    if( x === undef ) {

    }

})();
user113716
  • 318,772
  • 63
  • 451
  • 440
  • Thorough and accurate, but I'm not sure why you'd consider "letting broken code break" a better coding practice than using something else that is guaranteed to always work and is only slightly more complicated. – Tim Down Jun 26 '11 at 09:59
  • 1
    @Tim Down: Well they're personal preferences, but I don't believe in coding to accommodate poor coding practices. Broken code is an excellent instructor. Also, I find the *fix* to be visually hideous and entirely unintuitive. I understand its purpose, but then I think that once a person understands the reasons why they need it, they should no longer need it. Just my opinions. ;o) – user113716 Jun 26 '11 at 14:17
1

I would go with the second one, as "undefined" is not a reserved word. Example:

var obj = undefined;
undefined = {};

if(obj === undefined) {
    console.log("undefined 1");   
}

if(typeof obj === 'undefined') {
    console.log("undefined 2");   
}

Will only show "undefined 2" because the variable undefined can be changed.

Shaz
  • 15,637
  • 3
  • 41
  • 59
-1

This has been asked before, but the more common approach is to do this:

     typeof(x) == 'undefined'

See: JavaScript: undefined !== undefined?

Community
  • 1
  • 1
Mikola
  • 9,176
  • 2
  • 34
  • 41