Hoisting in JavaScript -

 

hoisting in js



Hoisting occurs because JavaScript engine will compile the code before its interpretation. The compiler actually considers var a = 2; as two different statements var a; and a = 2;. So the part of the compiler finds all the declaration first and then associate their assignment with their appropriate scopes.

* Hoisting is Javascript`s default behavior of moving declarations to the top
* JavaScript Declarations are Hoisted
* It can not work on let / const
* In anonymous function also, it can not work

Declaration - Assigning & Initialization

Declaration : (Hoisted)

- Declaration means simply giving a name to the and it`s data type ( by default Global without data type).
- we can`t see their value until we invoke/ call it.

Ex:
    var a;
    function a(){}

Assigning :
Assigning means simply storing the value in a variable.

Ex :
    a = 5 ;

Initialization : (Not Hoisted)

It means both declaring and assigning a intial value.

Ex :
    var a=5;


    Variable Hoisting..

     * Scope Means availability, and place  of the variables


    <script>

        // Variable Hoisting

        // console.log(abc);
        // console.log(msg);

        var abc = 99;
        var msg = 199;

        console.log(abc);
        console.log(msg);

    </script>

    Function Scope & Function Hoisting..
          <script>

        console.log(abc);

        function ramesh(){
            var abc = 99;  
            console.log(abc);  

        }
        ramesh();
        console.log(abc);

    </script>

        Block Scope..    <script>
        // Block Scope
        {
        const abc =999;  // let,const will not work on block scope
        var msg = 799;

        //console.log(abc);
        }
        console.log(abc);

    </script>