JS: Function Declaration vs Function Expression

By Xah Lee. Date: . Last updated: .

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

// function declaration
function f () {}

and

// function expression assigned to a variable
var f = function () {}

Function Declaration → Hoisting Name and Value

Function declaration will hoist the function name and definition to the top, but function expression assigned to variable will only hoist the name, not the definition.

Compare:

f(); // works. returns 3
function f () {return 3;}
g(); // TypeError: undefined is not a function
var g = function () {return 3;}

Function Declaration Must be Top Level

Named function form is declaration only if it is at top level of source code or top level of function body. When in elsewhere, its a named function expression.

// named function form is declaration only if it is at top level of source code or top level of function body.
// when in elsewhere, its a named function expression

var g = function f() { return 3; }; // no function declaration happens here. The f is treated as named function expression

g(); // returns 3

f(); // ReferenceError: f is not defined
// TypeError: undefined is not a function
h();
var h = function h () {return 3;};
// ReferenceError: bb is not defined
bb();
var aa = function bb () {return 3;};
// ReferenceError: bb is not defined
var aa = function bb () {return 3;};
bb();

The technical detail is fairly complicated. See: [• Named function expressions demystified By Juriy “Kangax” Zaytsev. At http://kangax.github.io/nfe/ , Accessed on 2014-07-13 ]

What Should You Do?

With ES2015 onward, always define function by const and arrow function.

const f = ((…) => { … });

This way, you don't have complexities of name hoisting, and you can define function anywhere, including inside if statement or any block construct {…}. The name will be local to that code block. Call to the function must happen after the definition.

[see JS: const Declaration]

[see JS: Arrow Function]

For pre ES2015, try to always use function expression var f = function () {…};, but any call must come after.

var f = function () {
    // };

// code to call f here. Must come after f.

Function Topic

  1. JS: Define Function
  2. JS: Arrow Function
  3. JS: Function Parameters
  4. JS: var/function Order
  5. JS: var Name Scope
  6. JS: Function Declaration vs Function Expression
  7. JS: Closure
  8. JS: Functional Programing
  9. JS: Function Call, Apply, Bind
  10. JS: Function Argument Default Value
  11. JS: Function Rest Parameters
  12. JS: Function Argument Destructure

  1. JS: Function Object
  2. JS: Function.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon