What is hoisting  mechanism and how it works in JavaScript ?

What is hoisting mechanism and how it works in JavaScript ?

Ā·

4 min read

In this blog, we'll know the complete detail of how hoisting mechanism occurs in JavaScript.

First, go through the definitionšŸŒŠ.

"Hoisting is Javascript default behaviour where variables and function declarations are top of their scope (global or local) before code execution"

In other words

"hoisting allows you to use functions and variables before they are declared."

I'm sure at this point,šŸ¤”

If youā€™ve ever wondered why you were able to call functions before you wrote them in your code, then check below.

Undefined vs ReferenceError:-

  • In Javascript an undeclared variable is assign the value undefined if check "typeof"

      console.log(typeof variable); // Output: undefined
    
  • ReferenceError is thrown when trying to access a previously undeclared variable.

console.log(variable); // Output: ReferenceError: variable is not defined

Hoisting variables:-

function hoist() 
{
 a = 20; 
var b = 100; 
}

hoist();

console.log(a); /* Accessible as a global variable outside hoist() function Output: 20 */

console.log(b); /* Since it was declared, it is confined to the hoist() function scope. We can't print it out outside the confines of the hoist() function. Output: ReferenceError: b is not defined */

All undeclared variables are global variablesšŸ˜Ž.

Therefore, it is recommended to always declare variables regardless of whether they are in a function or global scope.

Hoisting with Variables:-

Var

  • When the interpreter hoists a variable declared with var, it initializes its value to undefined.

  • The first line of code below will output undefined.

console.log(hoist); // Output: undefined
var hoist = 'The variable has been hoisted.';
  • JavaScript has hoisted the variable declaration. This is what the code above looks like to the interpreter:
var hoist;
console.log(hoist); // Output: undefined hoist = 'The variable has been hoisted.';

Function scoped variables

  • As weā€™ve seen above, variables within a global scope are hoisted to the top of the scope.

  • letā€™s look at how function scoped variables are hoisted

function hoist()
 {
 var message; 
console.log(message); 
message='Hoisting is all the rage!'
 }

hoist(); // Ouput: undefined

Let

  • Variables declared with the keyword let are block scoped and not function scoped.

  • In other words, variableā€™s scope is bound to the block in which it is declared and not the function in which it is declared.

console.log(hoist); // Output: ReferenceError: hoist is not defined ...
let hoist = 'The variable has been hoisted.';

This ensures that we always declare our variables first.

let hoist;

console.log(hoist); // Output: undefined
hoist = 'Hoisted'

Const

  • The const keyword was introduced in es6 to allow immutable variables.

  • That is, variables whose value cannot be modified once assigned.

  • With const, just as with let, the variable is hoisted to the top of the block.

if you try to reassign the value. This gives you error like below:-

const PI = 3.142;

PI = 22/7; // Let's reassign the value of PI

console.log(PI); // Output: TypeError: Assignment to constant variable.

and in terms of variable declaration

console.log(hoist); // Output: ReferenceError: hoist is not defined
const hoist = 'The variable has been hoisted.';
const PI;
console.log(PI); // Ouput: SyntaxError: Missing initializer in const declaration
PI=3.142;

Therefore, a constant variable must be both declared and initialised before use.

Hoisting with function:-

  • In Javascript, function declarations are also hoisted.

  • That means that you can call a function before it is defined in the code.

      foo();  // Output: "Hello"
    
      function foo() {
        console.log("Hello");
      }
    
    • Function expressions and arrow functions, on the other hand, are not hoisted.

    • If you try to call a function expression or an arrow function before it is defined, you will output like below.

        foo();  // Output: Cannot access 'foo' before initialization
      
        const foo=()=> {
          console.log("Hello");
        }
      

I hope this blog how hoisting works in JavaScript. It's definitely not as tricky or complicated as it sounds, but it does require us to breakdown the different use cases and trying different scenarios to understand how things work under the hood.

Did you find this article valuable?

Support Free Your Mind by becoming a sponsor. Any amount is appreciated!

Ā