Get super confident at JavaScript. Javascript Icon

I promise to change your JavaScript skills!

Function Declarations and Expressions

Functions can be created as a “declaration” or “expression”.

A function declaration uses the function keyword alongside a name:

function drink() {}


This article is from, our guide to all things functions!

Whereas a function expression assigns a function to a variable, such as var, let or const:

const drink = function() {};


A major difference between the two approaches is a feature called “hoisting”, which only a function declaration has.

A hoisted function declaration means it can also be accessed before it is defined:

// called before defined

function drink() {}

Just because you can, it doesn’t mean you should. This behavior may lead to unexpected surprises and is not very predictably written.

With the introduction of ECMAScript modules, hoisting has become less of a concern as functions are always imported at the top. Nevertheless it’s a good practice to only reference functions and variables that have already been defined.

A function expression does not support hoisting, as that is not how variables behave:

// ❌ Uncaught ReferenceError: drink is not defined

const drink = function() {};

A variable cannot be accessed before it is defined, as the JavaScript compiler will parse from the top-down.

We’ve silently introduced a new topic here too, named functions and anonymous functions.

Our function expression assigns an anonymous function, there is no name following the function keyword.

Let’s move onto learning about the difference between Named and Anonymous Functions.

Free eBooks:

Angular Directives In-Depth eBook Cover

JavaScript Array Methods eBook Cover

NestJS Build a RESTful CRUD API eBook Cover