3

I'm trying to understand when to use anonymous JavaScript functions.

State differences between the functions? Explain when you would use each.

var test1 = function(){
    $("<div />").html("test1").appendTo(body)
};

function test2() {
    $("<div />").html("test2").appendTo(body)
}

I think the answer is that one uses anonymous function and the other doesn't to replace an empty div element. Does that seem right?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Steve
  • 37
  • 3
  • no, it creates a blank div node with `test1` content and appends it to the `body`'s end. PS: deleted my answer since I misread the code in the question – zerkms Jun 03 '11 at 04:56
  • Just as a side note, **`append` is faster than `appendTo`**: *http://jsperf.com/html-vs-class* – Levi Morrison Jun 21 '11 at 16:11

3 Answers3

6

In your example it really doesn't make a huge difference. The only difference is that functions declared using function foo() { } are accessible anywhere within the same scope at any time, while functions declared using var foo = function () { } are only accessible after the code that does the assignment has run.

foo(); // ok
function foo() { ... };

bar(); // error, bar is not a function
var bar = function () { ... };
bar(); // ok

You usually use anonymous functions in cases where you don't need a named function, or where you're constructing objects:

arr.sort(function (a, b) { return a - b; });  // anonymous callback function

function MyObject() {
    this.foo = function () { ... }  // object constructor
}
deceze
  • 510,633
  • 85
  • 743
  • 889
1

You would use a function like the following (which is another type of anonymous function) when you do not want to pollute the global namespace:

(function() {
    var pollution = 'blablabla';

    function stinky() {
        // Some code
    }
})();
Petah
  • 45,477
  • 28
  • 157
  • 213
1

You may check John Resig's Secrets of JavaScript Libraries, especially page 47 for JavaScript function. Quite lengthy, but you'll learn more about JavaScript

OnesimusUnbound
  • 2,886
  • 3
  • 30
  • 40