1
function foo(bar) {
    // ...
}

and

foo = function(bar) {
    // ...
};

What is the benefit of one versus the other? The main benefit I see in the latter is not running into errors with a function name already being defined. However, there may be other benefits or drawbacks that aren't obvious. What are they (if any)?

Matt Huggins
  • 73,807
  • 32
  • 140
  • 214

2 Answers2

1

This has been asked a few times, this seems to be the best one.

Community
  • 1
  • 1
rosscj2533
  • 8,745
  • 7
  • 39
  • 55
1

There are other things that you can do with an anonymous function other than assigning it to a variable. You can for example execute it right away:

(function() { ... })();

This is sometimes used to create a scope for the code. Anything declared in the scope is local to it, and you can return a result to the code outside:

var a = (function() {

  var answer = 42;

  function display() { window.alert(answer); };

  return display;

})();

Now the variable a contains a function that displays the value of the variable answer, but the variable answer is local to the scope:

a(); // displays the value
display(); // not available
window.alert(answer); // not available

This pattern is for example used to create plugins for jQuery:

(function($) {

  $.fn.blackText = function() {
    return this.css('color', '#000');
  };

}(jQuery);

The jQuery object is sent into the scope as the $ parameter, that way the code in the scope can use the $ shortcut even if it has been turned off (using noConflict) outside the scope.

Guffa
  • 640,220
  • 96
  • 678
  • 956