Back to TIL
productivity

The difference between JavaScript function declarations

There are two common ways to declare a function in JavaScript:

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

Here’s the surprising difference:

// Declaration
foo();
function foo() {
  console.log("bar");
}
// → "bar"

Function declarations are hoisted, so you can call them before they appear in the code. But:

// Expression
foo();
var foo = function () {
  console.log("bar");
};
// → Uncaught TypeError: undefined is not a function

Function expressions assigned to var are not initialized until that line is executed, so calling them earlier throws an error.

While this may be old news for some, it was quite a welcome surprise for me today!