Welcome to the World of JavaScript Hoisting
JavaScript is a language full of intriguing behaviors, and hoisting is one of its most fascinating features. In this guide, we'll explore how JavaScript handles variable and function declarations, making your coding journey smoother and more predictable.

What is Hoisting?
Hoisting is JavaScript's default behavior of moving declarations to the top of their containing scope during the compile phase. This means that variables and functions can be used before they are declared in the code.
Variable Hoisting
Understanding var Hoisting
Variables declared with var are hoisted to the top of their scope and initialized with undefined. This can sometimes lead to unexpected results:
console.log(x);
var x = 5;
// Hoisted as:
var x;
console.log(x); // outputs: undefined
x = 5;During the creation phase, var x is hoisted and initialized with undefined.
The Role of let and const
With ES6, let and const were introduced to provide more predictable behavior through the Temporal Dead Zone (TDZ):
console.log(x);
let x = 5;
// Hoisted as:
// TDZ starts
let x;
console.log(x); // ReferenceError
x = 5;let and const declarations are hoisted but remain uninitialized in the TDZ.
The Role of let and const
Function Hoisting
Function Declarations
Function declarations are fully hoisted, meaning you can call them before they appear in the code:
sayHello();
function sayHello() {
console.log("Hello!");
}Function declarations are hoisted completely with their implementation.
// Hoisted as:
function sayHello() {
console.log("Hello!");
}
sayHello(); // Works perfectly!Function Expressions
Function expressions, however, are not hoisted in the same way:
sayHi();
var sayHi = function () {
console.log("Hi!");
};// Hoisted as:
var sayHi;
sayHi(); // TypeError: sayHi is not a function
sayHi = function () {
console.log("Hi!");
};Function expressions are hoisted as variables, not as functions.