98374598347934875
98374598347934875

Reputation: 535

Why JavaScript function declaration (and expression)?

I've seen others using the following pattern.

var bar = function foo(){};
console.log(bar); // foo()
console.log(foo); // ReferenceError: foo is not defined

But why? I can see the point if both were declared, but they're not. Why is the reason?

Upvotes: 16

Views: 664

Answers (5)

mpm
mpm

Reputation: 20155

When debugging an application, it is easier to know what is calling what in the call stack when "named" anonymous functions are used. So it is a way to give a name to an anonymous function for debugging purposes.

Try this and look at the callstack in a debugger:

myDiv = document.getElementById("myDiv");

myDiv.onclick = function OnClick(){
    debugger;
    //do something
}

Upvotes: 7

Esteban
Esteban

Reputation: 2579

The only reason I can imagine for this is to give the function a desired name. This helps debugging as the inspector uses the function object's name attribute. Try this:

var bar = function foo(){};
console.log(bar.name); // foo

If you put some real code inside foo and add a breakpoint to the JavaScript debugger in your browser, you will see the function as foo in the call stack.

Upvotes: 2

Leonard Garvey
Leonard Garvey

Reputation: 1547

The function definition (or literal) has 4 parts. 1. The reserved word function 2. An optional name which can be used by debuggers or by the function to call itself recursively. 3. The parameters and 4. The body of the function wrapped by { }

Outside of the function scope foo doesn't exist. But since you assigned the function to the variable bar you can call it using the method invocation bar and since bar is defined you can print it.

If you're interested in JavaScript you should really consider getting Douglas Crockford's book Javascript: The Good Parts

Upvotes: 0

Tim Down
Tim Down

Reputation: 324707

As mentioned by others, using the first form in your example (a named function expression) can help with debugging, although with the recent improvements in built-in developer tools in browsers, this argument is becoming less persuasive. The other reason for using a named function expression is that you can use the function name as a variable within the body of the function rather than the now-deprecated in ES5 arguments.callee.

However, named function expressions are incorrectly and problematically implemented in Internet Explorer < 9 and should generally be avoided when you're targeting those browsers. See Juriy Zaytsev's excellent article on the subject for more information.

Upvotes: 8

jbabey
jbabey

Reputation: 46657

They are naming an anonymous function because it makes debugging easier. When debugging, you will see a call to "foo" in the call stack rather than a bunch of calls to "anonymous".

Upvotes: 2

Related Questions