Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple question about Javascript functions, differences in invocation/definition

Tags:

javascript

Can someone please 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!

like image 881
Matthew Willhite Avatar asked Mar 30 '10 17:03

Matthew Willhite


1 Answers

Both are function expressions, basically the difference is that the first is named, and the second one 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 exist on some implementations, but it's non-standard.

Also, the name of function expressions it's useful for debugging, as you can inspect the call stack to see where you are.

This identifier is only accessible from inside the FunctionBody itself:

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

However there is a bug on the JScript implementation (in all versions of IE), which this name is leaked to its enclosing scope.

like image 74
Christian C. Salvadó Avatar answered Sep 25 '22 10:09

Christian C. Salvadó