Question

Wanted to get some input on this. When writing Javascript, I'm used to creating functions like this:

function firstThing() {
    console.log("first");
};

I was following a tutorial, and saw this setup. Using a variable assignment, and then passing an anonymous function, which then... becomes the function name. Is there a reason this would be used instead of the "traditional" way above?

var secondThing = function() {
    console.log("second");
};

Calling them is the same:

firstThing()
secondThing()
Was it helpful?

Solution

This is called a function expression:

var foo = function() {}

and this is a function declaration:

function foo() {}

A major difference is that function declarations are "hoisted". Behind the scenes, a function declaration is "hoisted" to the top of its scope and assigned to a variable name - effectively the same as a function expression.

Consider this:

foo(); //logs 'abc'
function() {
  console.log('abc');
}

That works fine because foo will be hoisted. With a function expression, this will fail:

foo(); //foo is not defined!
var foo = function() {
  console.log('abc');
}

One thing that's awesome about function expressions is that you can assign their value with an IIFE (Immediately Invoked Function Expression) and have private values and functions like this:

var myFunc = (function() {
  function thisWillBeMyFunc() {
    doOne();
    doTwo();
    doThree();
  }

  function doOne() {
    console.log('Action 1!');
  }
  function doTwo() {
    console.log('Action 2!');
  }
  function doThree() {
    console.log('Action 3!');
  }

  return thisWillBeMyFunc;
}());

myFunc(); //logs the actions

doOne(); //error - not defined!

Live demo (click).

Oh, the wonderful power and flexibility of JavaScript!

OTHER TIPS

There is another difference. The first creates a named function, the second option will create an anonymous function.

When you are viewing the stack trace the second option will appear as an anonymous function the first will appear named. You can see how the first approach would give you some insight when debugging.

Some further references here and here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top