Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use named function expressions?

We have two different way for doing function expression in JavaScript:

Named function expression (NFE):

var boo = function boo () {   alert(1); }; 

Anonymous function expression:

var boo = function () {   alert(1); }; 

And both of them can be called with boo();. I really can't see why/when I should use anonymous functions and when I should use Named Function Expressions. What difference is there between them?

like image 586
Afshin Mehrabani Avatar asked Mar 11 '13 10:03

Afshin Mehrabani


People also ask

Why would you use a function expression?

The case for function expressions Function expressions are invoked to avoid polluting the global scope. Instead of your program being aware of many different functions, when you keep them anonymous, they are used and forgotten immediately.

What is a named function expression?

Named functions can be either declared in a statement or used in an expression. Named function expressions create readable stack traces. The name of the function is bound inside its body, and that can be useful. And we can use the name to have a function invoke itself, or to access its properties like any other object.

What is the purpose of named function in JavaScript?

Named Functions: In JavaScript, named functions are simply a way of referring to a function that employs the function keyword followed by a name that can be used as a callback to that function. Normal functions with a name or identifier are known as named functions.

What's the difference between a function declaration and function expression?

The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined.


2 Answers

In the case of the anonymous function expression, the function is anonymous — literally, it has no name. The variable you're assigning it to has a name, but the function does not. (Update: That was true through ES5. As of ES2015 [aka ES6], often a function created with an anonymous expression gets a true name [but not an automatic identifier], read on...)

Names are useful. Names can be seen in stack traces, call stacks, lists of breakpoints, etc. Names are a Good Thing™.

(You used to have to beware of named function expressions in older versions of IE [IE8 and below], because they mistakenly created two completely separate function objects at two completely different times [more in my blog article Double take]. If you need to support IE8 [!!], it's probably best to stick with anonymous function expressions or function declarations, but avoid named function expressions.)

One key thing about a named function expression is that it creates an in-scope identifier with that name for the function within the functon body:

var x = function example() {      console.log(typeof example); // "function"  };  x();  console.log(typeof example);     // "undefined"

As of ES2015, though, a lot of "anonymous" function expressions create functions with names, and this was predated by various modern JavaScript engines being quite smart about inferring names from context. In ES2015, your anonymous function expression results in a function with the name boo. However, even with ES2015+ semantics, the automatic identifier is not created:

var obj = {      x: function() {         console.log(typeof x);   // "undefined"         console.log(obj.x.name); // "x"      },      y: function y() {         console.log(typeof y);   // "function"         console.log(obj.y.name); // "y"      }  };  obj.x();  obj.y();

The assignment fo the function's name is done with the SetFunctionName abstract operation used in various operations in the spec.

The short version is basically any time an anonymous function expression appears on the right-hand side of something like an assignment or initialization, like:

var boo = function() { /*...*/ }; 

(or it could be let or const rather than var), or

var obj = {     boo: function() { /*...*/ } }; 

or

doSomething({     boo: function() { /*...*/ } }); 

(those last two are really the same thing), the resulting function will have a name (boo, in the examples).

There's an important, and intentional, exception: Assigning to a property on an existing object:

obj.boo = function() { /*...*/ }; // <== Does not get a name 

This was because of information leak concerns raised when the new feature was going through the process of being added; details in my answer to another question here.

like image 86
T.J. Crowder Avatar answered Sep 27 '22 21:09

T.J. Crowder


Naming functions is useful if they need to reference themselves (e.g. for recursive calls). Indeed, if you are passing a literal function expression as an argument directly to another function, that function expression cannot directly reference itself in ES5 strict mode unless it is named.

For example, consider this code:

setTimeout(function sayMoo() {     alert('MOO');     setTimeout(sayMoo, 1000); }, 1000); 

It would be impossible to write this code quite this cleanly if the function expression passed to setTimeout were anonymous; we would need to assign it to a variable instead prior to the setTimeout call. This way, with a named function expression, is slightly shorter and neater.

It was historically possible to write code like this even using an anonymous function expression, by exploiting arguments.callee...

setTimeout(function () {     alert('MOO');     setTimeout(arguments.callee, 1000); }, 1000); 

... but arguments.callee is deprecated, and is outright forbidden in ES5 strict mode. Hence MDN advises:

Avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself.

(emphasis mine)

like image 33
Mark Amery Avatar answered Sep 27 '22 20:09

Mark Amery