Skip to main content

Command Palette

Search for a command to run...

Hoisting in Javascript

Published
2 min read
Hoisting in Javascript
D

Full Stack Developer. I have hands on experience in crafting web applications using TypeScript, Next , React ,TailwindCSS. I have also worked with PostgresDB and AWS S3. I have also developed dAPP based upon ERC 20 , ERC 721 tokens.

In Javascript (JS), variables and functions can be accessed before initializing it without any error anywhere in the program. This is known as Hoisting.

Javascript creates a Global Execution Context, GEC even before a program starts running. In the GEC, memory allocation and code execution takes place.

Let us try to understand hoisting in the variables with the following code.

var a = 10;

console.log(a);

This function would display the value of "a" as "10" in the browser window.

Screen Shot 2022-01-05 at 2.14.36 PM.png

Now let's move the console.log(a) at the top.

console.log(a);

var a = 10;

Screen Shot 2022-01-05 at 2.21.11 PM.png

We could see that the console.log(a) displays undefined.

To understand it better we could move the debugger to console.log(a) in the Sources window in the browser. Here, in the Global Execution Context, we could see that even before initialising the variable var a =10, the memory is allocated to a as undefined.

Screen Shot 2022-01-05 at 2.31.15 PM.png

The execution context is created before the code starts running and the memory is allocated to each and every variables and functions.

Now let us understand in the case of the function.

function qwerty() {
    console.log("Keys don't start with ABCD");
}

qwerty();
console.log(qwerty);

Here, the function qwerty() is called at the end of the program & it displays the output in the console as "Keys don't start with ABCD".

console.log(qwerty);

prints the entire function.

Screen Shot 2022-01-07 at 12.49.48 PM.png

Screen Shot 2022-01-05 at 3.00.24 PM.png

If we call the function "qwerty()" before it's being written then we see that it prints the contents of console.log inside of the function.

qwerty();

function qwerty() {
     console.log("Keys don't start with ABCD");
}

12.png

11.png

However, console.log(qwerty) will print the function qwerty() with the string "Keys don't start with ABCD"

console.log(qwerty);
function qwerty() {
       console.log("Keys don't start with ABCD");
}

2.png

During the compile phase, the Javascript engine stores the variables and function declaration in the memory allowing the user to access them in the code before they are actually written.

Moreover, only the declaration variables are hoisted and not their assignment.