Javascript functions like “var foo = function bar() …”?

You are seeing a named function expression (NFE).

An anonymous function expression is where you assign a function without a name to a variable1:

var add = function () {
  console.log("I have no own name.");
}

A named function expression is where you assign a named function to a variable (surprise!):

var add = function addNums() {
  console.log("My name is addNums, but only I will know.");
}

The function’s name is only available within the function itself. This enables you to use recursion without necessarily knowing the “outside name” of the function – even without having to set one in the first place (think callback functions).

The name you choose shadows an existing name, so if another addNums is defined elsewhere it will not be overridden. This means you can use any name you like without fear for scoping problems or breaking anything.

In the past you would have used arguments.callee to refer to a function inside itself without knowing its name. But support for that is being removed from JavaScript2, so NFEs are the correct way to do this nowadays.

Here is a lot of stuff to read on the topic: http://kangax.github.io/nfe/


1 Assigning it to a variable is not necessary, it just serves as an example to distinguish it from a plain function declaration. It could be any other context where JS expects an expression (a function argument, for example).

2 You will receive an error if you have strict mode in effect and try to use arguments.callee.

Leave a Comment