Understanding Hoisting in Nested Scopes in JavaScript

A comprehensive guide to hoisting in nested scopes with practical examples

Max N
3 min readMar 19, 2024

In JavaScript, hoisting is a mechanism where variable declarations are moved to the top of their respective scope during compilation. This means that you can use variables before they’re declared without getting an error. However, when it comes to nested scopes, things get a bit more complicated. Let’s dive into understanding how hoisting works in nested scopes in JavaScript.

Firstly, let’s define what we mean by nested scopes. Simply put, nested scopes refer to situations where one scope is contained within another scope. For example, consider the following code snippet:

function outerFunction() {
const x = 'outside';
if (true) {
const y = 'inside';
console.log(x); // this logs 'outside'
console.log(y); // this logs 'inside'
}
}
outerFunction();

In this example, x is defined in the global scope while y is defined in the inner scope created by the if statement. We say that y is nested inside the scope of x. Now, let's see how hoisting affects these nested scopes.

Consider the following modified version of our previous example:

function outerFunction() {
console.log(x); // this doesn't…

--

--

Max N

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