Hoisting In JavaScript

Hoisting In JavaScript

·

4 min read

Greetings, fellow coders👋

Let's get to know the Hoisting in JavaScript.

Hoisting

Hoisting is a JavaScript mechanism where variables and functions can be accessed even before initializing values without getting errors and this happens during the 1st phase (Memory Creation Phase) of the Execution Context.

Whoever doesn't know about the Execution Context. Let me explain

Execution context

Whenever a JavaScript Program is run the Execution context is created in two phases, i) Memory Creation Phase and ii) Code Execution Phase.

Let's get to know in detail

1) Memory Creation Phase

Memory Creation Phase is the first phase where it skims through the entire program and stores variables with undefined values and functions with a copy of the function.

2) Code Execution Phase

The Code Execution Phase again skims through the entire program line by line and re-assigns with new values in the memory.

Let's understand with an example:

Example 1: Variable Hoisting

getLang(); // JavaScript
console.log(y); // undefined
var y = 7;
function getLang() {
 console.log("JavaScript");
}
console.log(y); // 7

The above code snippet could throw an error in other languages whereas in JavaScript because of the Execution Context, it doesn't throw any error.

We Know in the Memory Creation Phase where it allocates memory to the variables with undefined and for functions with the copy of the function itself. The `y` is stored with undefined and getName function with the copy of the function itself.

In the Code Execution Phase where it re-assigns the values of variable `y=7`.

Output 1:

JavaScript
undefined
7

Example 2:

However, if we remove var y = 7 then it gives an error Uncaught ReferenceError: y is not defined.

Because, In the Memory Creation Phase, the y is not stored with undefined since there is no declaration for y.

getLang(); // JavaScript
console.log(getLang); // f getLang(){ console.log("JavaScript); }
console.log(y); // Uncaught Reference: y is not defined.

function getLang(){
    console.log("JavaScript");
}

Output 2:

JavaScript
Æ’ getLang(){
    console.log("JavaScript");
}
Uncaught Reference: y is not defined.

Let's try with the Arrow Function

Arrow Functions are treated as variables not as a functions. So, in the Memory Creation Phase, it is allocated as undefined.

Let's try to understand with an example:

Example 3: Arrow Function

getLang(); // Uncaught TypeError: getLang is not a function
console.log(getLang);
var getLang = () => {
    console.log("JavaScript");
}
// The code won't execute as the first line itself throws an TypeError.

In the above code snippet, the `getLang` doesn't behave like a function rather it's a variable. In the Memory Creation Phase, it allocates undefined to the getLang. So, It throws an error.

Output 3:

Uncaught TypeError: getLang is not a function

Let's see more examples to understand the concept

Example 4: Variable Hoisting

console.log(x); // undefined
var x = 10;
console.log(x); // 10

Explanation:

Even though console.log(x)appears beforevar x = 10, JavaScript hoists the variable declarationvar xto the top of its scope during the Memory Creation Phase.

So, whenconsole.log(x)is executed,xhas been declared but not yet assigned a value, resulting inundefined.

Later, when xis assigned the value10,console.log(x)outputs10.

Output 4:

undefined
10

Example 5: Function Hoisting

hello(); // "Hello, world!"

function hello() {
    console.log("Hello, world!");
}

Explanation:

The functionhellois hoisted to the top of its scope during the Memory Creation Phase, so it's accessible before its actual declaration in the code.

When hello()is called before its declaration, JavaScript doesn't throw an error because the function declaration has already been hoisted.

As a result, hello()executes successfully and logs"Hello, world!".

Output 5:

Hello, world!

Example 6: Function Expression

sayHello(); // TypeError: sayHello is not a function

var sayHello = function() {
    console.log("Hello!");
};

Explanation:

In this example, var sayHellois hoisted to the top of its scope during the Memory Creation Phase.

However, the function expressionfunction() { console.log("Hello!"); }itself is not hoisted.

When sayHello()is called before the function expression, JavaScript recognizessayHelloas a variable but doesn't find it assigned to a function yet because it is assigned with an undefined value.

As a result, attempting to callsayHello()before its assignment throws a TypeError.

Output 6:

Uncaught TypeError: sayHello is not a function

These examples demonstrate how hoisting works with variable declarations, function declarations, and function expressions.

and that's it!

Conclusion

That's fantastic! You can already imagine how you can use this Hoisting.

Additionally, make sure to explore the documentation and the examples on the Hoisting. They provide a wealth of information and inspiration.

I'm glad I could help. If you have any more questions along the way, feel free to reach out. Happy coding!

Â