Demystifying Hoisting in JavaScript Variables: A Beginner’s Guide

Understanding How JavaScript Variables Behave Behind the Scenes

Max N
2 min readMar 13, 2024
Photo by Tao Yuan on Unsplash

Have you ever wondered why you can use a variable before it’s declared in your JavaScript code? This seemingly magical behavior is known as hoisting. In this article, we’ll delve into the concept of hoisting in JavaScript variables, demystify how it works behind the scenes, and provide you with practical examples to solidify your understanding.

What is Hoisting?

Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that regardless of where variables are declared in your code, they are hoisted to the top of their function or global scope.

Hoisting with Variables

When it comes to variables, only the declaration is hoisted, not the initialization. Let’s look at an example:

console.log(myVar); // Output: undefined
var myVar = 'hoisted';

In this example, even though we’re trying to access myVar before it's declared, JavaScript hoists the declaration to the top, resulting in undefined. It's important to note that only the declaration is hoisted…

--

--

Max N
Max N

Written by Max N

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