Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does one reuse `undefined`? [duplicate]

In John Resig's slideshow on how he was building jQuery 1.4, he mentioned a point where he added an undefined variable to the jQuery closure because "we can re-use (the variable)".

undefined is not an ordinary variable:

> var undefined = 4
  undefined
> undefined
  undefined

Therefore, we know that undefined is not a variable. So why would an undefined be re-undefined in the jQuery source?

Slide 31

like image 905
Brian Avatar asked Jul 25 '13 14:07

Brian


2 Answers

Because in some JavaScript engines it's possible to set undefined to a value. This is to make sure undefined is really undefined.

like image 191
Rocket Hazmat Avatar answered Oct 29 '22 10:10

Rocket Hazmat


Additionally to +Rocket Hazmat's answer, you can reduce the file size after compression a bit, when your code uses undefined frequently. That's because a local variable undefined may have its name mangled by the compressor, while the global undefined may not:

foo === undefined;
//      ^----- don't touch this, put "undefined" in the compressed result

(function (undefined) {
    foo === undefined;
})();
// may however be mangled to
(function(u){foo===u})();
like image 44
Boldewyn Avatar answered Oct 29 '22 12:10

Boldewyn