A simple question about Javascript functions, call / definition differences

Can someone explain the difference between the following function definitions?

var alertMessage = function alertMessage(message) { alert(message); } var alertMessage = function(message) { alert(message); } 

What are the implications of each? Thanks!

+6
javascript
source share
2 answers

Both are expressions of functions, the main difference is that the first is named and the second is anonymous.

For example:

 var test = function test(message) { alert(message); }; var test1 = function(message) { alert(message); }; test.name; // "test" test1.name // "" or "anonymous" 

Note. The name property of function objects exists on some implementations, but it is non-standard.

In addition, the name of the functional expressions is useful for debugging, as you can check the call stack to see where you are.

This identifier is only available inside FunctionBody itself:

 (function foo(){ typeof foo; // "function" })(); typeof foo; // "undefined" 

However, there is an error in the implementation of JScript (in all versions of IE), and this name has leaked into its private area.

+2
source share

Both definitions are function expressions, unlike function declarations or functions created by the Function constructor. Both assign a function to the alertMessage variable. The difference is that the first function is called, and the second is anonymous.

Named functions are commonly used in function declarations, such as

 function alertMessage(message) { ... } 

In this case, the function declaration creates a variable in the current scope, called alertMessage , which refers to this function. Function declarations go up to the top of the current area, so you can call declared functions before they are defined in your js file.

A named function used in a function expression (for example, the original question) does not create this variable or does not rise at the top of the execution area, therefore, by convention, most function expressions are anonymous. The only advantage of naming a function is that the variable name is associated with the function (although, as the CMS mentions, it depends on the implementation), and the function name is derived from the toString method. This can be useful during debugging (instead of having Firebug (?) Output for a huge list of anonymous function calls).

More information at MDC

+2
source share

All Articles