Function declaration vs. function expression in JavaScript

Function declaration

A function declaration defines a function that will be executed when it is invoked.

function shot() {
  // body
}

Function expression

A function expression is similar to a function declaration, with the difference that it can be stored in a variable. As soon as the function is defined with an expression, it is invoked.

const shot = function() {
  // body
}

Differences

1. Hoisting:

  • In JavaScript, hoisting refers to the availability of the variables and the functions at the beginning of the code.
  • Function declarations are similar to var; they will be automatically hoisted, whereas function expressions will not be hoisted.
  • In simple terms, function declarations will load before any other code, and function expressions will load when the interpreter reaches it.

Defining a function using function declaration:

  • JavaScript
Console

Defining a function using function expression:

  • JavaScript
Console

2. Callback:

  • In JavaScript, a callback is a function that is passed to another function as an argument.
  • If a callback is a function declaration, it will be available in the global scope, which is not necessary most of the time.
  • If a callback is a function expression, it will not be available outside of the function that uses it.

Callback using function declaration:

  • JavaScript
Console

Callback using function expression:

  • JavaScript
Console

3. IIFE:

  • An Immediately-invoked Function Expression (IIFE) is a way to execute functions immediately, as soon as they are created.
  • As the name suggests, IIFEs can be created using function expression.
  • JavaScript
Console

Summary

These are some basic differences between function declaration and function expression. The usage of them depends on the use case. If the function is required globally, use function declaration. If the scope of the function needs to be limited, use function expression.

Free Resources