22 Feb 2024
Hoisting in JavaScript is a mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means that regardless of where variables and functions are declared within their scope, they are treated as if they are declared at the top.
However, it's important to understand that only the declarations are hoisted, not the initializations or assignments. Let's break down how hoisting works for variables and functions separately:
-
Variable Hoisting:
console.log(x); // undefined var x = 5;This code actually behaves like:
var x; console.log(x); // undefined x = 5;So, the variable declaration
var x;is hoisted to the top, but the assignmentx = 5;remains in place.It's worth noting that
letandconstdeclarations are hoisted to the top of their block scope but are not initialized until the actual declaration statement is encountered in the code. This means they are not accessible before the line they are declared on. -
Function Hoisting:
foo(); // "Hello, world!" function foo() { console.log("Hello, world!"); }This works because function declarations are hoisted entirely to the top, so the
foofunction is available even before its declaration in the code.However, function expressions, such as those created with
var,let, orconst, do not exhibit hoisting like function declarations do. For instance:bar(); // TypeError: bar is not a function var bar = function() { console.log("Hello, world!"); }This fails because the variable
baris hoisted but initialized withundefined, hence not callable at that point.
⭐Note: It's recommended to declare and initialize variables at the top of their scope to avoid unexpected behavior due to hoisting. Understanding how hoisting works helps in writing cleaner and more predictable JavaScript code.