JSJan 28, 2014 · 2 min read

Defining Undefined

Comparing to undefined directly is fine for local variables, but global undefined can be reassigned in some engines. A look at typeof vs strict equality, idiomatic JS patterns, and why IIFEs guard against it.

I came across a snippet of code that my colleague used to default configuration variables to true:

JavaScript
function someObj(config){
  someVar = config.someVar === undefined ? true : config.someVar;
}

I wanted to see how that pattern was used in other places, and if there was another way of setting the default of a configuration value to true. That search took me down a rabbit-hole of the undefined, and here is what I found...

typeof and undefined

It appears that a more common pattern was:
JavaScript
someVar = typeof config.someVar === 'undefined' ? true : config.someVar;

The argument was made that because undefined is a global variable that can be overridden in some JavaScript engines, it is insufficient to compare to undefined. For more information, check out http://designpepper.com/blog/drips/redefining-undefined.

Idiomatic JS

According to Idiomatic JS, they distinguish two approaches for checking if a value is undefined:
Global Variables
JavaScript
typeof variable === "undefined"
Local Variables
JavaScript
variable === undefined

Redefining Undefined

Its kind of unsettling to know that it is possible that some JavaScript engines would allow users to redefine undefined. It explains why developers sometimes wrap their code in an immediately-invoked function expression:
JavaScript
(function(window, $, undefined){
 //some code
})(window, jQuery);

This does a couple of things:

  • Redefines the window object as a local object, shortening the scope chain and allegedly yielding performance gains. A few extra bytes may also be eked when minified/uglified, as the window variable can be shortened to w.
  • Protect your jQuery code form conflicting with other libraries. See Avoid Conflicts with Other Libraries
  • Protect usage of undefined within your code. By passing in just two parameters to a function that takes three arguments, the third argument is (correctly) assigned a value of undefined.