What is the purpose of passing arguments to anonymous functions in this manner?

JavascriptJqueryGoogle Closure-Compiler

Javascript Problem Overview


> Possible Duplicate:
> How do JavaScript closures work?

I was playing around with the Google Closure Compiler, putting in random code to see what it would do.

It rewrote one of my functions to look something like this:

(function(msg) { console.log(msg); })("Hello World!");​​​​​​​

Where it appears that "Hello World" is the argument passed as msg to the anonymous function preceding it. I was looking at it for a moment, and had thought that I had seen something similar in jQuery plugins that look something like:

(function( $ ) {
  ...
})(jQuery); 

Which now makes more sense to me, in the scope of conflicts with $. But what is the primary reason or purpose for passing arguments into an anonymous function like this? Why wouldn't you simply define the arguments as variables within the function? Is there any performance or flexibility advantage to writing functions like this?

Javascript Solutions


Solution 1 - Javascript

There is one significant difference connected also to scope. The following code:

(function(msg) { console.log(msg); })("Hello World!");​​​​​​​

is in some circumstances cleaner in terms of namespace pollution than this:

var msg = "Hello World!";
console.log(msg);

because the second code leaves variable after it is no longer needed, but may interfere with other parts of the code.

This is especially important when you execute the mentioned code outside any other function: in such case msg variable would be available everywhere on the page, as global variable.

Solution 2 - Javascript

Basically, it's always a good idea to keep your code wrapped in this: (function(){/*code*/}()); to prevent your vars from colliding with other peoples vars.

I think the main thing closure compiler is getting at is saving the 5 characters:var  and =.

Solution 3 - Javascript

It depends a bit on the context. There are some conditions where the compiler won't try to inline any function at all (if the scoping function contains "eval" for instance). If this is a in global scope and you are running in ADVANCED mode, it is simply that the inlining opportunity appeared after the compiler stop trying to inline functions (or there is a bug in the inlining code and it missed the opportunity). If you run your sample output through the compiler in ADVANCED mode, you get this:

console.log("Hello World!");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyle MaceyView Question on Stackoverflow
Solution 1 - JavascriptTadeckView Answer on Stackoverflow
Solution 2 - JavascriptDevin RhodeView Answer on Stackoverflow
Solution 3 - JavascriptJohnView Answer on Stackoverflow