Function Hoisting: Declarations vs. Expressions

Quick Explainer

JBallin
JBallin
Oct 30, 2017 · 2 min read

Function Declaration

Basic function definition.

function foo() {
console.log('bar')
}
foo(); // bar

All functions require the function keyword (prior to ES6). Function declarations require a name after that keyword ( foo). They cannot be anonymous functions (functions without a name will throw an error).

Function Expression

Storing a function definition, as an expression, in a variable.

var foo = function() {
console.log('bar')
};
foo(); // bar

A variable called foo was declared and assigned to an anonymous function (although we could’ve given it a name).

Note: Function expressions end with semicolons, declarations do not.


Hoisting

Never heard of hoisting? Read this first.

Function Declarations

Always hoisted to the top of their scope.

foo('bar'); // barfunction foo(x) {
console.log(x);
}

Even though foo was defined after it was called, it still worked because of hoisting. It was executed as:

function foo(x) {
console.log(x);
}
foo('bar');

Function Expressions

Function expression definitions are not hoisted! The variable declaration is hoisted (just like any other variable) but you won’t be able to call the function until the variable is assigned.

foo1('bar'); // ReferenceError: foo1 is not defined
foo2('bar'); // TypeError: foo2 is not a function
var foo2 = function(x) {
console.log(x);
};

The first error says “I’ve never heard of foo1!” while the second says “I’ve heard of foo2 but it’s not a function…”. Let’s see how it was executed:

var foo2;
foo1('bar');
foo2('bar');
foo2 = function(x) {
console.log(x);
};

The foo2 variable declaration was hoisted to the top but hadn’t been assigned to anything so it was undefined. undefined is not a function, so we got that error when we tried undefined('bar'). Note that the assignment stayed where it was.


I like to remember a function declaration as if I’m declaring something in a speech to a large group of people. People will hear what I say immediately.

I know that a function expression must be stored in a variable because expressions need to be stored somewhere. And I know that variables are hoisted to the top of their scope but their assignment remains where it was.


Great video showcasing the different hoisting behaviors: Udacity

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade