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
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(); // works. returns 3
function f () {return 3;}
g(); // TypeError: undefined is not a function
const g = function () {return 3;};

[see JS: 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.

// 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

const 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();
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 ES2015 onward, 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 JS: 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 JS: const Declaration]

[see JS: Arrow Function]

For pre ES2015, try to always use

var f = function (…) {…};

Call of the function must happen after the definition.

Function Topic

  1. JS: Define Function
  2. JS: Functional Programing
  3. JS: Arrow Function
  4. JS: Function Parameters
  5. JS: f Declaration vs Expression
  6. JS: Closure
  7. JS: Function Call, Apply, Bind
  8. JS: Function Argument Default Value
  9. JS: Function Rest Parameters
  10. JS: Function Argument Destructure
  11. JS: Function Object
  12. JS: Function.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.