Search⌘ K
AI Features

Variable Hoisting

Explore how JavaScript hoists variable declarations to the top of their scope, causing variables to hold undefined before assignment. Discover differences between function declarations and expressions in hoisting, and learn best practices for writing clear, predictable code.

We'll cover the following...

Variable Hoisting

What do you think the following code will log to the console? Take a guess and then run the code to check.

Javascript (babel-node)
console.log(x); // -> ?
var x = 5;
console.log(x); // -> ?
console.log(y); // -> ?

The second console statement prints 5 as expected, but the first prints undefined. But the last statement prints an error. What gives? Why do we see an error for y but not for x?

The JavaScript Engine

This is because the JavaScript engine alters the structure of our code before it runs it.

Variable declarations are hoisted, or moved, to the top of their available scope. We’re currently in the global scope, so they’ll be hoisted to the top. The code that ...