Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between following two javascript code? [duplicate]

In some Javascript code which uses immediate function, it has argument window or document like the following:

(function (window, document) {
  ...
})(window, document);

However, window and document are global objects and can be directly accessed as follow:

(function () {
  var userAgent = window.navigator.userAgent;
  ...
  var el = document.getElementById(...)
  ...
})();

What are the differences between the above two codes. Which is better way and why?

like image 442
ntalbs Avatar asked Aug 27 '13 02:08

ntalbs


2 Answers

Two reasons I can think of:

1) Local variables are the first in the scope chain, so their access is faster than globals (with faster I mean insignificantly faster).

2) Inside the function, window and document are local variables, so their names can be minimified:

(function (w, d) {
//var userAgent = w.navigator.userAgent;

)(window, document);
like image 170
Marlon Bernardes Avatar answered Oct 26 '22 10:10

Marlon Bernardes


What are the differences between the above two codes. Which is better way and why?

In all practicality and usage in browsers only, there's no appreciable difference.

That said, there's a very slight performance increase that comes from referencing local variables instead of globals.

Also, it allows the flexibility of swapping out the real window by a mock version; this could be useful during testing and in certain environments where some of the objects are not available and must be replaced.

Btw, there's another kind of argument you could pass, which is undefined; it goes like this:

(function(undefined) {
    // your code
}());

You don't actually pass anything to the outer function and by doing so you make sure that undefined has not been tampered with; pedantic people like myself would just void 0 for that purpose though :)

like image 33
Ja͢ck Avatar answered Oct 26 '22 09:10

Ja͢ck