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?

2
  • 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 Commented Jun 3, 2011 at 4:56
  • Just as a side note, append is faster than appendTo: jsperf.com/html-vs-class Commented Jun 21, 2011 at 16:11

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

Comments

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
    }
})();

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.