I was recently asked to explain the difference between a JavaScript function expression and a function declaration. This one always caught me out until I created a mental model to allow me to understand it. Firstly though, let’s clear up which is which:

A function expression looks like this

var expressYourself = function() {
// I resolve to a value
}

…where as a function definition looks like…

function definingMyself() {
// I am a reference point only
}

The key difference here is that a function expression always resolves to a value. This value can then be used anywhere that a normal value might be expected – as an argument to another function call for example.

Conversely, a function declaration is what JavaScript calls a “statement”. Statements are more like definitions or actions. Examples of statements include:

  • if/else
  • try/catch
  • for loops

A full list of statement types is available on MDN.

Expression’s in the wild – IIFE’s FTW!

A common use of a function expression is the IIFE (Immediately Invoked Function Expression). This looks like

(function imGettingIIFE() {
	// immediately invoked!
})();

This might look a bit like a declaration until you notice the extra parenthesis before the function keyword and immediately after the closing curly brace. These act to make JavaScript interpret whatever is inside the parenthesis as an expression. We can, therefore, immediately call the result of the expression by appending a pair of parenthesis. Nice!

Trying to do the same thing with a function declaration would cause a syntax error

function notAnIIFE() {
	// errors
}();

This is because JavaScript see’s your code a bit like…

function notAnIIFE() {
	// normal function declaration here
}
(); // WAAAAATTT! Random braces just hanging out here

So there you have it. A simple way to remember the different between function expression and declarations in JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.