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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)