Share the post

Hello All, Today in this topic we will discuss the concept called hoisting in JavaScript. In this topic, we will discuss What is Hoisting in JavaScript? Example to understand hoisting in a better way.

What is Hoisting in JavaScript? 

Hoisting means using the variable before it gets declared. Simply means you can able to use a variable by assigning the value to variable use it & then declare the variable. We can understand the concept in a better way by using the below example.

Example : 

We will look into this concept by using three small examples which are shown below :


    <h1>JAVASCRIPT : Hoisting</h1>





    console.log("Example decalre the variable after assigning the value");
    a = "this is string"; //assign the variable value
    console.log("a " + a);
    var a; // declare

    console.log("Example decalre the variable but not assigned");
    console.log("b " + b);
    var b = "this is string"; // declare

    console.log("Example decalre value using let keyword after assigning the value");
    c = "this is string"; //assign the variable value
    console.log("c " + c);
    let c; // declare


Output :


In the first example, We have declared the variable after assigning the value to variable a. This concept is called Hoisting. In the next example, We have to use the variable without assigning the value to the variable & declare it, therefore we get the error as undefined. We have declared the value using the let keyword after assigning value to c, but in output, we can clearly see that it logs the error like ‘Uncaught ReferenceError: Cannot access ‘c’ before initialization at index.html:27′. In this way, it proves that Hoisting can be used only for variables not for the let & const keyword & the variable needs to be assigned with value otherwise it will show the error of undefined.

Leave a Comment