Hoisting In JavaScript

Hoisting In JavaScript

When a code block is executed in JavaScript, JavaScript scan all the variables inside the current scope and moves it to the top of the scope. This is called hoisting. Consider the below code:

    a = 'Hello'

    console.log(a);  // Hello

    var a;

The above code is successfully executed and gives the desired output as although the variable has been used before it was even declared. This is because of hoisting.

When var variables are hoisted, they are assigned undefined as their value. Which means var variables can be accessed before they are declared and also before they are initialized. However, while doing so will result in the code executing successfully, it will not give us the desired and instead give undefined as the output:

    console.log(a); // undefined

    a = 'Hello'

    var a; 

However, when it comes to let and const variables, they are hoisted but not initialized with undefined. const variables require to be initialized when they are declared, so trying to access them without doing so will result in a SyntaxError. While trying to access let variables without giving them an initial value will result in a ReferenceError.

const:

    console.log(a); // SyntaxError

    a = 'Hello'

    const a;

let:

    console.log(a); // ReferenceError

    a = 'Hello'

    let a;