Published on

Javascript Hoisting .md file

Authors
  • avatar
    Name
    Ganesh Negi
    Twitter

What is Hoisting in JavaScript ?

It's a way of managing the variable and function declaration in JavaScript. So, hoisting ensures no matter where we declare our varialbe of function,

it always go at the top while executing our code.

Let's understand with example:-


console.log(a);
console.log(b);
let a;
let b = 1;

Variable Hoisting:-

The behavior of hoisting varies depending on whether a variable is declare using var, let , const.

Hoisting With Var:-

When you declare a variable using var, it is hoisted to the top of its current scope.

Let's understand with example:-

console.log("x");

var x;

// Output: undefined

If we declare variable with let and const it will give reference error because in let and const they have created a temporary dead zone.

Because here variable does not have default value like var.

The Temporal dead Zone:-

The TDZ (Temporal Dead Zone) starts at the starting of the variable's enclosing scope and ends when it is declared.

Accessing the variable in this TDZ throws a reference error.

Function hoisting:-

Function declarations are hoisted, function hoisting allows you to call a funciton before it is defined.


hello(); // Hello Ganesh

funciton hello() {
  console.log("Hello Ganesh!);
}

Note:

Only function declarations are hoisted , not funciton expressions.