Demystifying Variable Hoisting in JavaScript

Lift the Hood on Hoisted Bindings

Max N
2 min readFeb 23, 2024
Photo by Fejuz on Unsplash

JavaScript exhibits unique behavior around variable and function declarations getting implicitly “hoisted” to the top of code blocks. Understanding how hoisting works demystifies head-scratching behavior and allows leveraging it properly.

Let’s dig into how declaration hoisting happens in JavaScript, why it matters when writing code, and key takeaways in working with this mechanism effectively. Mastering hoisting intricacies will level up coding skills!

What is Hoisting?

Hoisting in JavaScript refers to variable and function declarations getting internally lifted to the top of scope blocks before code execution.

For example:

console.log(variable); // undefined
var variable = "assigned";

Logically you would expect an error trying to reference variable before declaration. However, the variable declaration behind the scenes was hoisted to the top:

// How code executes with hoisting:
var variable; // Declaration hoisted
console.log(variable); // undefined
variable = "assigned";

Voila! The declaration hoists avoiding an error allowing access before assignment.

Why Does Hoisting…

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.