Creating Functions

Function Declarations and Expressions

Todd Motto by Todd Motto Google Developer Expert Icon Google Developer Expert
JavaScript Icon

Learn JavaScript the right way

Premium JavaScript courses to skyrocket your skills to the top.

5x Courses: Basics, Masterclass, HTML5 APIs, DOM, Testing with Jest.

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

A function declaration uses the function keyword alongside a name:

function drink() {}


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.

Keywords or Variables

Named and Anonymous Functions »