0

I am wondering what the difference is between this:

(function(msg) {
    alert(msg);
}('Hi'));

and this:

alert('Hi');

Because when you use an anonymous function, you can't run it twice, right? You can't do this:

(function(msg) {
    alert(msg);
}('Hi')('Goodbye'));

So what's the point of an anonymous function?

This:

(function(msg) {
    alert(msg);
}('Hi'));

gets the same output as this:

alert('Hi');

Could someone tell me what the difference is?

Oliver Ni
  • 2,312
  • 7
  • 27
  • 41
  • 1
    It's not about the anonymous function, it's about closures and scope, see here http://stackoverflow.com/questions/8228281/what-is-this-construct-in-javascript – elclanrs Nov 29 '13 at 22:16
  • 1
    In this case - there is no point. There is a point if you declare some variables in the function - in that case the variables will remain in the anonymous function's scope and not be visible from anywhere else. – Vatev Nov 29 '13 at 22:19

3 Answers3

3

The main difference is that it has its own scope. Example:

(function(msg) {
  var x = msg; // local variable in the scope
  alert(x);
}('Hi'));

// the variable x doesn't exist out here

That is useful when you for example create a function in the scope, and expose it outside. The function still has access to the scope even when executed outside it. That way the function can keep a state, without exposing the state globally:

var f = (function(msg) {
  var cnt = 1;
  return function(){
    alert(msg + ' ' + cnt);
    cnt++;
  };
}('Hi'));

f(); // shows "Hi 1"
f(); // shows "Hi 2"
Guffa
  • 640,220
  • 96
  • 678
  • 956
2

Your example shows an Anonymous Function that is self-executing. The self-executing Function closes off scope, so you can do things like this:

var count = (function(){
  var c = 0;
  return function(){
    return c++;
  }
})();
console.log(count()); console.log(count());

In your first example nothing different will occur. An Anonymous function, just has no name, so this:

document.getElementById('whatever').addEventListener('click', function(){alert('wow')});

and

function wow(){
  alert('wow');
}
document.getElementById('whatever').addEventListener('click', wow);

do the same thing.

StackSlave
  • 10,198
  • 2
  • 15
  • 30
  • No, that would execute the function on the spot, before the event is fired. A function name is basically a variable that is executed with `()`. – StackSlave Nov 29 '13 at 23:10
1

the anonymous function is when you declare a function without name i.e

function(){
  ...
}

Your example is an inmediate function, here you can hide properties and functionality (using closures, this is complex I recommend you The secrets of JS Ninja, but is a intermediate lvl book.), so you can use this when use the module pattern:

(function(msg) {
    alert(msg);
}('Hi'));

BTW this is a good resource about patterns in JS: http://addyosmani.com/resources/essentialjsdesignpatterns/book/