Cobwwweb logo

WTF is Hoisting?

Aug 07, 2020 JavaScript, WTF

Hoisting is a JavaScript concept in which variable, function, and class definitions are hoisted (lifted) to the top of their lexical environment (their scope) before execution.

Consider the following:

console.log(foo) // => undefined

var foo = "bar"

In many other programming languages, this code would result in an error because we're trying to use foo before we've defined it. JavaScript works a little differently, as the code isn't executed strictly like it is written. Instead, under the hood, it works more like this:

var foo

console.log(foo) // => undefined

foo = "bar"

Variables declared with var are hoisted to the top of their scope (the global scope in this example). This results in the variable being initialized but not assigned.

ES6 introduced let and const, which behave differently. While they are technically hoisted, an error will be thrown if they are used before they are declared.

console.log(foo) // => Cannot accesss 'foo' before initialization

let foo = "bar"

That's hoisting in nutshell, although there are plenty of additional nuances to explore. This article does a fantastic job of breaking them down. I highly recommend the read if you want to explore the topic further. And, though a little more technical, the MDN reference is always a great resource.

Did you learn something or find this article interesting?

If so, why not

Want to receive exactly one email every month with new articles, tools, and references I've discovered? Sign up below. (More info here.)