DEV Community

Cover image for JavaScript Hoisting: The Magic Trick
s mathavi
s mathavi

Posted on

JavaScript Hoisting: The Magic Trick

some variables in JavaScript seem to work before they're even declared.

Types of Hoisting:
1.var is hoisted — with undefined as default value

console.log(a); // undefined
       var a = 10;
Enter fullscreen mode Exit fullscreen mode

2.let and const are hoisted — but not initialized

They are placed in a "Temporal Dead Zone (TDZ)" from the start of the block until their declaration is encountered.

 console.log(b); //  Reference Error
       let b = 20;

Enter fullscreen mode Exit fullscreen mode

3.Function Hoisting
!!Function declarations are hoisted with their full definition.
greet(); // works

function greet() {
         console.log("Hello!");
       }
Enter fullscreen mode Exit fullscreen mode

Non-Hoisting Scenarios
1.let and const in Temporal Dead Zone:

 console.log(num); // ReferenceError
let num = 10;





Enter fullscreen mode Exit fullscreen mode

2. Arrow Functions with const or let:

    add(3, 4); //ReferenceError

       const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

Only const add; is hoisted, not the function definition.
3.Class Declarations

 const obj = new MyClass(); //  ReferenceError

class MyClass {
  constructor() {
    this.name = "JS";
  }
}

Enter fullscreen mode Exit fullscreen mode

let’s meet again in the next topic

Top comments (0)