Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var undefined = void 0; vs jquery's closure vs ...?

Reading underscore's source, I noticed the use of void 0 instead of undefined. I know in some browsers undefined can be overwritten, and that a solution to this, in many cases, is just omitting an argument when calling a function, or return;-ing. In fact, for minification purposes, it makes much more sense to do this rather than using void 0.

Also, jquery's aproach to this issue:

(function (window, undefined){
  /* ... */
}(window));

seems to be better in every sense. It is much more readable than void 0, can be minified further, and might give some tiny performance boost as explained in the linked answer.

OK, void 0 appears about 6 times in underscore and 9 in backbone, so it doesn't make much of a difference. So, my question is: Is there any reason or corner cases where void 0 is preferable?

like image 595
spelufo Avatar asked Nov 11 '22 12:11

spelufo


1 Answers

Here's an example of why the "undefined argument" thing can be a horrible idea.

Let's say you get used to doing it. And you start applying it to other functions too, like this:

function doSomething(undefined) {
    // blah blah blah
    if( something == undefined) {
        // problem
    }
}

All good, right?

Let's say that this function is an event handler.

someElement.onclick = doSomething;

Oh dear. doSomething gets passed an Event object, which is most certainly not undefined!

void 0 is much more robust, as it doesn't rely on a quirk or an assumption to work.

like image 59
Niet the Dark Absol Avatar answered Nov 15 '22 12:11

Niet the Dark Absol