What is the purpose of passing-in undefined?

There are two reasons for that:

1) If undefined is a variable in the function scope rather than a global object property, minifiers can reduce it to a single letter thus achieving a better compression rate.

2) Before ES5*, undefined was a property of the global object without write-protection. So it could be overwritten, resulting in strange and unexpected behavior. You could do something like this:

var test = 123;
undefined = 123;
if (test === undefined){
   // this will actually be true, since undefined now equals 123
}

By having an function argument undefined (the name actually does not matter) which you don’t pass a parameter to, you could make sure you have a variable which really is undefined so you can test “undefinedness” against this variable.

Btw. the safest method to test for undefined is: typeof ( var ) === 'undefined'

(*) With EcmaScript 5, the global properties undefined, NaN and Infinity became readonly. So with its general adoption in all modern browsers – of course with the exception of IE 9 – overwriting those values was not possible anymore.

Leave a Comment