Hoisting is one of the magical spells or magic itself that happens in javascript. In hoisting, variables (and function) declaration is moved to the top.
To understand hoisting it is important to know in brief about variable declaration and initialization. As we scroll through this blog, knowing about the declaration and initialization will be very helpful, as var, let and const behave differently in different situations.
Variable declaration is declaring a variable or specifying a variable with the name var name
. While initializing a variable is just giving value to it var name = "hashnode"
. Declaring a variable first and then initializing it can work for var
and let
but not for const
. Let's demonstrate it with code:
// const example
const name;
name="hashnode";
console.log(name);
Output:
Hoisting in Variables
Let's understand how hoisting takes place for variables.
var
console.log(name);
var name="hashnode";
So, normally what should happen is the above code should give us some error instead we get an output as undefined
. Because the hoisting states that the declaration is to be moved to the top, the variable is declared but not initialized. After hoisting, the code seems to be as followed:
var name;
console.log(name);
name="hashnode";
let and const
let and const are also hoisted but unlike var, they throw a reference error as they are being used before initializing and declaring it. This happens because let and const are said to be in a temporal dead zone where if a variable is accessed without being initialized with a value gives a reference error.
console.log(name);
let name="hashnode";
console.log(name);
const name="hashnode";
Both will result in the same output.
For more references:
https://www.digitalocean.com/community/tutorials/understanding-hoisting-in-javascript
https://www.programiz.com/javascript/hoisting
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let