[javascript] typeof !== "undefined" vs. != null

I often see JavaScript code which checks for undefined parameters etc. this way:

if (typeof input !== "undefined") {
    // do stuff
}

This seems kind of wasteful, since it involves both a type lookup and a string comparison, not to mention its verbosity. It's needed because undefined could be renamed, though.

My question is:
How is that code any better than this approach:

if (null != input) {
    // do stuff
}

As far as I know, you can't redefine null, so it's not going to break unexpectedly. And, because of the type-coercion of the != operator, this checks for both undefined and null... which is often exactly what you want (e.g. for optional function parameters).

Yet this form does not seem widespread, and it even causes JSLint to yell at you for using the evil != operator.

Why is this considered bad style?

This question is related to javascript coding-style

The answer is


_x000D_
_x000D_
function greet(name, greeting) {_x000D_
  name = (typeof name !== 'undefined') ?  name : 'Student';_x000D_
  greeting = (typeof greeting !== 'undefined') ?  greeting : 'Welcome';_x000D_
_x000D_
  console.log(greeting,name);_x000D_
}_x000D_
_x000D_
greet(); // Welcome Student!_x000D_
greet('James'); // Welcome James!_x000D_
greet('Richard', 'Howdy'); // Howdy Richard!_x000D_
_x000D_
//ES6 provides new ways of introducing default function parameters this way:_x000D_
_x000D_
function greet2(name = 'Student', greeting = 'Welcome') {_x000D_
//  return '${greeting} ${name}!';_x000D_
console.log(greeting,name);_x000D_
}_x000D_
_x000D_
greet2(); // Welcome Student!_x000D_
greet2('James'); // Welcome James!_x000D_
greet2('Richard', 'Howdy'); // Howdy Richard!
_x000D_
_x000D_
_x000D_


You can also use the void operator to obtain an undefined value:

if (input !== void 0) {
    // do stuff    
}

(And yes, as noted in another answer, this will throw an error if the variable was not declared, but this case can often be ruled out either by code inspection, or by code refactoring, e.g. using window.input !== void 0 for testing global variables or adding var input.)


good way:

if(typeof neverDeclared == "undefined") //no errors

But the best looking way is to check via :

if(typeof neverDeclared === typeof undefined) //also no errors and no strings

You shouldn't really worry about undefined being renamed. If someone renames undefined, you will be in a lot more trouble than just a few if checks failing. If you really want to protect your code, wrap it in an IFFE (immediately invoked function expression) like this:

(function($, Backbone, _, undefined) {
    //undefined is undefined here.
})(jQuery, Backbone, _);

If you're working with global variables (which is wrong already) in a browser enviroment, I'd check for undefined like this:

if(window.neverDefined === undefined) {
    //Code works
}

Since global variables are a part of the window object, you can simply check against undefined instead of casting to a string and comparing strings.

On top of that, why are your variables not defined? I've seen a lot of code where they check a variables existence and perform some action based on that. Not once have I seen where this approach has been correct.


if (input == undefined) { ... }

works just fine. It is of course not a null comparison, but I usually find that if I need to distinguish between undefined and null, I actually rather need to distinguish between undefined and just any false value, so

else if (input) { ... }

does it.

If a program redefines undefined it is really braindead anyway.

The only reason I can think of was for IE4 compatibility, it did not understand the undefined keyword (which is not actually a keyword, unfortunately), but of course values could be undefined, so you had to have this:

var undefined;

and the comparison above would work just fine.

In your second example, you probably need double parentheses to make lint happy?


If you are really worried about undefined being redefined, you can protect against this with some helper method like this:

function is_undefined(value) {
   var undefined_check; // instantiate a new variable which gets initialized to the real undefined value
   return value === undefined_check;
}

This works because when someone writes undefined = "foo" he only lets the name undefined reference to a new value, but he doesn't change the actual value of undefined.


_x000D_
_x000D_
var bar = null;_x000D_
console.log(typeof bar === "object"); //true yes _x000D_
//because null a datatype of object_x000D_
_x000D_
var barf = "dff";_x000D_
console.log(typeof barf.constructor);//function_x000D_
_x000D_
_x000D_
console.log(Array.isArray(bar));//falsss_x000D_
_x000D_
_x000D_
console.log((bar !== null) && (bar.constructor === Object)); //false_x000D_
_x000D_
console.log((bar !== null) && (typeof bar === "object"));  // logs false_x000D_
//because bar!==null, bar is a object_x000D_
_x000D_
_x000D_
console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function"))); //false_x000D_
_x000D_
console.log(typeof bar === typeof object); //false_x000D_
console.log(typeof bar2 === typeof undefined); //true_x000D_
console.log(typeof bar3 === typeof undefinedff); //true_x000D_
console.log(typeof bar2 == typeof undefined); //true_x000D_
_x000D_
console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]")); //false
_x000D_
_x000D_
_x000D_


If the variable is declared (either with the var keyword, as a function argument, or as a global variable), I think the best way to do it is:

if (my_variable === undefined)

jQuery does it, so it's good enough for me :-)

Otherwise, you'll have to use typeof to avoid a ReferenceError.

If you expect undefined to be redefined, you could wrap your code like this:

(function(undefined){
    // undefined is now what it's supposed to be
})();

Or obtain it via the void operator:

const undefined = void 0;
// also safe

_x000D_
_x000D_
(function(){_x000D_
_x000D_
  var a= b = 3;_x000D_
  var ed = 103;_x000D_
  _x000D_
})();_x000D_
_x000D_
_x000D_
_x000D_
//console.log(ed); //ed is not defined_x000D_
_x000D_
console.log("a defined? " + (typeof a !== 'undefined')); //no define_x000D_
console.log("b defined? " + (typeof b !== 'undefined')); //yes define_x000D_
console.log(typeof(b)); //number_x000D_
console.log(typeof(4+7));   //number_x000D_
console.log(b); //3_x000D_
console.log(typeof("4"+"7")); //string_x000D_
var e= "ggg";_x000D_
console.log(typeof(e)); //string_x000D_
 var ty=typeof(b);_x000D_
console.log(ty); //number_x000D_
console.log(typeof false); //boolean_x000D_
console.log(typeof 1); //number_x000D_
console.log(typeof 0); //number_x000D_
console.log(typeof true); //boolean_x000D_
_x000D_
_x000D_
console.log(typeof Math.tan);  //function_x000D_
console.log(typeof function(){}); //function _x000D_
_x000D_
if(typeof neverDeclared == "undefined") //no errors_x000D_
if(typeof neverDeclared === "undefined") //no errors_x000D_
_x000D_
//if(neverDeclared == null) //showing error _x000D_
_x000D_
_x000D_
console.log(typeof {a:1}); //object_x000D_
console.log(typeof null); //object_x000D_
console.log(typeof JSON); //object_x000D_
console.log(typeof Math); //object_x000D_
console.log(typeof /a-z/); //object_x000D_
console.log(typeof new Date()); //object_x000D_
_x000D_
console.log(typeof afbc); //undefined_x000D_
//console.log(typeof new);//error_x000D_
_x000D_
document.write("<br> * oprator as math ");_x000D_
var r=14*"4";_x000D_
document.write(r);_x000D_
_x000D_
document.write("<br> + oprator as string ");_x000D_
var r=14+"44";_x000D_
document.write(r);_x000D_
_x000D_
document.write("<br> Minus Operator work as mathematic ");_x000D_
var r=64-"44";_x000D_
document.write(r);_x000D_
_x000D_
_x000D_
document.write("<br>");_x000D_
console.log(typeof(4*"7")); //returns number_x000D_
console.log(typeof(4+"7")); //returns string_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 
_x000D_
Interview Question in JavaScript
_x000D_
_x000D_
_x000D_


I've actually come across if (typeof input !== 'undefined') in this scenario where it's being used to provide default function parameters:

function greet(name, greeting) {
  name = (typeof name !== 'undefined') ?  name : 'Student';
  greeting = (typeof greeting !== 'undefined') ?  greeting : 'Welcome';

  return `${greeting} ${name}!`;
}

greet(); // Welcome Student!
greet('James'); // Welcome James!
greet('Richard', 'Howdy'); // Howdy Richard!

ES6 provides new ways of introducing default function parameters this way:

function greet(name = 'Student', greeting = 'Welcome') {
  return `${greeting} ${name}!`;
}

greet(); // Welcome Student!
greet('James'); // Welcome James!
greet('Richard', 'Howdy'); // Howdy Richard!

This is less verbose and cleaner than the first option.