JavaScript Hoisting 101

August 3, 2024 (1mo ago)

Article cover

Hoisting is a phenomenon in JavaScript where you can access variables and functions even before initializing them.

Let’s look at an example of a code block below 👇

getName();    
console.log(age);
 
var age = 22;
function getName() {
console.log("Name: ", "Abdul Rehan");
};

Before I execute this code, what do you expect to see? 🤔

We’re attempting to access the getName() function and the age variable before they've been initialized.

Output to review — i

In the case of variables, it shows undefined, but for functions, it displays the results, whether it’s a function statement or when invoked. It’s quite strange how it works since we don’t see what’s happening behind the code.

Whenever you execute code, an execution context is created in two phases: memory creationand code execution. As soon as the code starts executing, memory is allocated to each variable and function. Even before the code starts executing, memory is allocated.

Global Scope

If we dig into the global scope, we’ll see that the variable x has already been allocated memory even before the code is executed.

Memory allocation — i

In the case of functions, we get the actual copy of the function stored in memory instead of an undefined placeholder.

Function copy — i

Until now, we have seen function invocation and variable access after the function statement and variable declaration. Let’s see what happens when we move the function invocation and variable access to the top.

Again, we have put the debugger on the first line of the code. Even before this first line’s execution, the variables and functions are already in the memory space.

Memory Allocation — ii

Function copy — ii

Now, if everything is executed line by line, you can observe the output shown in the console 👇

Output to review — ii

Moving forward, we have seen enough about undefined, but have you ever thought about the difference between undefined and not defined? By observing the code block below, if I comment out the variable declaration and then execute the code, what will happen?

getName();
console.log("VARIABLE: ", x);
console.log("FUNCTION STATEMENT: ", getName);
 
// var x = 22;
function getName() {
console.log("Name: ", "Abdul Rehan");
}

We have not reserved memory for the variable x in the global memory space. So, when it tries to access x and it is not found in the global object, JavaScript will throw a reference error saying x is not defined.

Output to review — iii

Connect with me 🍕

If you have any questions, feel free to reach to me on LinkedIn 🚀