DEV Community

Discussion on: Named Function vs. Variable Function?

Collapse
 
mellen profile image
Matt Ellen • Edited

The distinction goes a bit deeper than your two examples. MDN provides a good explanation, but I'll give a quick overview:

There are function declarations:

function add(a, b)
{
  return a+b;
}

Function declarations must be named.

There are named function expressions:

const plus = function add(a, b)
{
  return a+b;
};

And there are anonymous function expressions:

const plus = function(a, b)
{
  return a + b
};

As far as I understand, the way you write functions is largely a style choice.

The main differences are:

  • As you know, only function declarations get hoisted, so you can actually use a function that is declared before you declare it in code:
add(1,3); //works
plus(1,3); // ReferenceError: can't access lexical declaration `plus' before initialization
function add(a, b)
{
  return a+b;
}
const plus = function namedadd(a, b)
{
  return a+b;
};
  • Named functions can be used recursively
const fibN = function fib(i)
{
  if(i == 1) return 1; 
  if(i == 2) return 1; 
  return fib(i-1) + fib(i-2);
};

Of course you can also use the variable name (fibN in this example) to make the function recursive.

  • If you name a function then the name is used in stack traces, rather than the variable name.
const err1 = function erroriser()
{
  throw Error('error1');
};

const err2 = function()
{
  throw Error('error2');
};

err1();

// Error: error1 debugger eval code:3:9
//    erroriser debugger eval code:3
//    <anonymous> debugger eval code:1

err2();

// Error: error2 debugger eval code:8:9
//    err2 debugger eval code:8
//    <anonymous> debugger eval code:1
  • Function expresions get semicolons inserted after their closing brace (if there isn't one there).
function foo()
{
}// no semicolon will be inserted

const bar = function()
{
}// semicolon will be inserted