Javascript hoisting in action

concepts and implementations

Hoisting Javascript Variables and Functions

Have you ever seen some code like the snippet below in Javascript and thought, WTF? Look at line 2, then look at line 8.


The above snippet is Hoisting in action.

Hoisting is a Javascript behavior that can be easily overlooked or even unknown to developers. This tutorial will walk you through the basics of hoisting, why it’s important and some best practices.

In Javascript, hoisting means that variable and function declarations are processed before any code is executed. This behavior breeds several results:

  • When reading code it may appear that a variable or function is being used before being defined
  • Declaring any variable or function in code is equal to declaring it at the top

Before we get into some example code, we need to take a quick detour into Javascript Scoping. If you understand the basics of Scoping in Javascript, hoisting will make more sense to you.

Scoping in Javascript

Variables declared OUTSIDE of functions are called GLOBAL. Variables declared INSIDE functions become LOCAL to that function. Local variables have local scope, they can ONLY be accessed within the function in which they were defined.

global vs. local scope

Hoisting in Javascript

Declaration vs. Definition vs. Simultaneous D&D

  • Declaration — HOISTED
  • Definition — NOT HOISTED
  • Simultaneous D&D — Declaration is HOISTED, Definition NOT HOISTED
declaration vs. definition vs. simultaneous d&d


variable hoisting

Because of Hoisting, lines 3–4 and 7–8 produce the same result in Javascript. Line 7 does not throw a reference error. This is the most simple representation of Hoisting.


The exact same concept applies to functions.

function hoisting

Line 2 spits out the expected ‘something’ response because the function declaration was hoisted to the top of the code.

Line 8 spits out an err b/c even though the variable declaration WAS hoisted, the definition was NOT.

Best Practices

  • Always define variables before you use them.
  • Variables should be declared at the top of the function scope to make your code readable and to make scope(and intent) clear to other developers.
  • It is usually best to define functions lower in the code to keep them out of the way.

So that’s it for Hoisting in Javascript. Let us know your thoughts and questions on twitter. Keep after it.

If you like this article, please recommend and share to help others find it!