JavaScript: Function Declaration vs Function Expression

By Xah Lee. Date: . Last updated: .

When you use the keyword function to define function, there are some complexities.

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

// function declaration
function f () {}

and

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

Function Declaration → Hoisting Name and Value

Function declaration will implicitly move the function name and definition to the top.

Function expression assigned to variable will only hoist the name, not the definition.

Compare:

f(); // returns 3
function f () {return 3;}
// error: Uncaught ReferenceError: Cannot access 'f' before initialization
g();
const g = function () {return 3;};

[see var Declaration Order]

Function Declaration Must be Top Level

Named function form

function name () {}

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

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

g(); // 3

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

Tip

With JS2015, you can always define function by const and arrow function.

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

or

const f = function () {};

Call of the function must happen after the definition.

Advantage:

  1. No complexities of name hoisting [see var Declaration Order]
  2. Can move function anywhere, including inside if statement or any block construct {}. The name will be local to that code block.

[see const Declaration]

[see Arrow Function]

JavaScript Function

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc