Both definitions are function expressions, as opposed to function declarations, or functions created by the Function
constructor. They both assign a function to the variable alertMessage
. The difference is that the first function is named, while the second is anonymous.
Named functions are usually used in function declarations, eg
function alertMessage(message) { ... }
In that case, the function declaration creates a variable in the current scope called alertMessage
that references that function. Function declarations are hoisted to the top of the current scope, so you can call declared functions before they're defined in you js
file.
A named function used in a function expression (such as the original question) does not create this variable, or get hoisted to the top of the execution scope, so by convention most function expressions are anonymous. The only benefits to naming a function expression are that the name
variable is bound within the function (although as CMS mentions, this is implementation dependent) and the function name is output from the function's toString
method. This can be useful during debugging (rather than having Firebug output (?)
for a huge list of anonymous function calls).
Much more detail at MDC