Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of using a named function expression? [duplicate]

I'm going through this blog about the difference between function declarations and function expressions.

It gives these two examples. They call the first an "anonymous function expression" and the second a "named function expression."

// anonymous function expression
var a = function(){
   return 3;
}

// named function expression
var b = function bar(){
   return 3;
}

I tested these two in Chrome's JS console and I see the following:

a()
=> 3

b()
=> 3

bar()
=> bar is not defined

My question is: In the second function expression declaration, what is the point of "bar"? In general, why does one ever use a named function expression?

like image 878
User314159 Avatar asked Dec 08 '22 12:12

User314159


2 Answers

Some people prefer to do it like this because if errors occur, your functions have names. It's mostly a matter of preference and how often you have trouble with unnamed functions.

You don't normally see it used in a var declaration, but instead when declaring callbacks:

callbackFunction(function success() { ... }, function fail() { ... })

That way you know which argument is which, they're labelled, and if one of them fails you get a precise indication of which one broke.

like image 149
tadman Avatar answered Dec 11 '22 10:12

tadman


var b = function bar(){
   return 3;
}
bar()
=> bar is not defined

The identifier bar is only available inside of the function. Try

var b = function bar() {
    console.log(bar);
}
b();

why does one ever use a named function expression?

To allow referencing a function expression that was not assigned to a reachable or constant variable, e.g. for recursion in an IEFE.

Also, named functions show up different during debugging, e.g. in call stack (trace)s or breakpoint listings. Often you can use a (named) function declaration instead of a function expression, see also http://blog.niftysnippets.org/2010/03/anonymouses-anonymous.html.

like image 40
Bergi Avatar answered Dec 11 '22 10:12

Bergi