Skip to main content

Command Palette

Search for a command to run...

JavaScript: Hoisting?

Updated
2 min read
S

I love learning about technology and sharing that with others

Hoisting

In javascript, all the variables and function declaration is moved to the top This is irrespective of the scope, which means it will happen in both global and local scope.

Hoisting doesn't work with initialization it works only with declarations,

let was introduced in ES6 and it is only scoped block level means it is not being accessed outside the block.

working of let and const is same but the thing is const value can be modified but cannot be reassigned.

//mutation is allowed in const
 const gh=1;
 console.log(gh+1);

 //reassignmen is not allowed

 gh=3;

screenshot_99.png

screenshot_15.png

Hoisting will not work with let and const

let will give reference error

Const will give syntax error

screenshot_16.png

Let and var


//let will create a new lexical environment and binds the fresh value rather than keeping the old reference

//this function prints 5 times 6
for(var i=1; i<6; i++){
    setTimeout(function(){
       console.log(i);
    },1000)
 }

 //this function prints 1 --> 5
 for(let i=1; i<6; i++){
    setTimeout(function(){
       console.log(i);
    },1000)
 }

Examples of Hoisting


//Hoisitng with variables

x=12;
console.log("value of x is : ",x);
var x;


//Hoisting with function
addNumber();

function addNumber() {

   console.log("adding numbers")
}


//Hoisting with local scope
//here declaration of the y willl move at the top since it is declarared locallly
function subtractNumbers() {

    y=10;
    console.log(y);
    var y;
}


subtractNumbers();

//Hositing --> global scope --> let
//Error received : app.js:32 Uncaught ReferenceError: Cannot access 't' before initialization

// t=3;
// console.log(t);
// let t;


//syntax Error : app.js:40 Uncaught SyntaxError: Missing initializer in const declaration
// p=78;
// console.log(p);
// const p;



//this will give undefined
//if we try to access a variable that is not defined it will give us error undefined.
console.log(u);
var u=12;

//let const function class --> all of them are hoisted


function doSomething1(arr){
    //i is known here but undefined
    //j is not known here

    // console.log(i);       --> here i will be undefined
    // console.log(j);

    for(var i=0; i<arr.length; i++){
        //i is known here
    }

    //i is known here
    //j is not known here

    console.log(i);   // here i value is 4
    // console.log(j);

    for(let j=0; j<arr.length; j++){
        //j is known here
    }

    //i is known here
    //j is not known here

    console.log(i);    // here i value is 4
    // console.log(j);
}

doSomething1(["Thalaivar", "Vinoth", "Kabali", "Dinesh"]);
38 views

More from this blog

H

hashcodehub

271 posts

Consistent, Passionate and Organized :)