JavaScript Functions – Function Declaration as Var vs Function

functionsjavascript

More and more I'm seeing functions being declared like

var foo = function() {

    // things
};

Instead of how I had learned, like

function foo() {

    // things
}

What's the difference? Better performance? Scope? Should I be using this method?

Best Answer

var foo = function() {} defines a variable that references an anonymous function.

function foo() {} defines a named function foo.

Either can be passed by name as function parameters and either can be instantiated if the intended use is for OOP.

At the end of the day, which one you use is largely dictated by your specific use-case (Javascript is fun like that ;)). If you end up using the former, I would strongly suggest that you name the function:

var foo = function MY_function() {}. This naming convention helps your debugger callstack not be useless.