JavaScript hoisting is a behavior in which variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code execution. This means that you can use variables and functions before they are declared in the code. However, only the declarations are hoisted, not the initializations. This can lead to unexpected results if not properly understood.
In JavaScript, variable declarations are hoisted to the top of their containing function or global scope. This means you can reference a variable before it's declared.
Example 1: Using var
console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5
Explanation: In the first console.log
, x
is undefined
because the declaration var x
is hoisted, but not the assignment x = 5
. After the assignment, x
has the value 5
.
Example 2: Using let
and const
console.log(y); // Output: ReferenceError: Cannot access 'y' before initialization
let y = 10;
console.log(z); // Output: ReferenceError: Cannot access 'z' before initialization
const z = 20;
Explanation: With let
and const
, declarations are hoisted but are not initialized. They are in a "temporal dead zone" from the start of the block until the declaration is encountered. Therefore, accessing them before declaration results in a ReferenceError
.
Function declarations are hoisted completely, meaning both the function name and its implementation are moved to the top of their scope.
Example 3: Function Declarations
console.log(add(2, 3)); // Output: 5
function add(a, b) {
return a + b;
Explanation: The function add
is hoisted to the top, so it can be called before its declaration.
Example 4: Function Expressions
console.log(subtract(5, 3)); // Output: TypeError: subtract is not a function
var subtract = function(a, b) {
return a - b;
};
Explanation: In this case, subtract
is a variable that holds a function expression. The variable declaration is hoisted, but the assignment (the function definition) is not. Therefore, calling subtract
before its initialization results in a TypeError
.
var
declarations are hoisted and initialized with undefined
, while let
and const
declarations are hoisted but not initialized.Understanding hoisting helps avoid common pitfalls and write more predictable JavaScript code.
Published By: Krishanu Jadiya
Updated at: 2024-08-08 00:23:09