JavaScript hoisting is a fundamental concept that affects how variables and functions are declared and accessed within the execution context. Hoisting allows JavaScript to move variable and function declarations to the top of their scope before code execution.
In simple terms, hoisting enables you to use variables and functions before they are declared in the code.
JavaScript hoisting works differently for variables and functions. Let's break it down:
Function declarations are fully hoisted, meaning you can invoke a function before defining it in the code.
hello(); // Works fine
function hello() {
console.log("Hello, world!");
}
Output:
Hello, world!
Since function declarations are hoisted entirely, the JavaScript engine moves the entire function to the top of its scope.
Variable hoisting behaves differently depending on whether var
, let
, or const
is used.
var
When variables are declared with var
, they are hoisted to the top but initialized with undefined
.
console.log(a); // undefined
var a = 10;
console.log(a); // 10
Here, a
is hoisted but remains undefined
until it is assigned a value.
let
and const
Variables declared with let
and const
are hoisted but not initialized. Accessing them before declaration results in a ReferenceError
due to the temporal dead zone (TDZ).
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 20;
Function expressions and arrow functions do not get fully hoisted. If they are assigned to a variable using var
, the variable is hoisted but remains undefined
.
console.log(sayHello); // undefined
var sayHello = function() {
console.log("Hello!");
};
sayHello(); // Works now
This is different from function declarations, which are fully hoisted.
let
and const
instead of var
– This prevents accidental access before initialization.'use strict'
) – Helps catch undeclared variables and enforce cleaner coding practices.JavaScript hoisting is an essential concept that affects how your code runs. Understanding its behavior with variables and functions can help you write cleaner, more predictable code. By following best practices like using let
and const
and declaring functions properly, you can avoid common pitfalls related to hoisting.
Now that you understand hoisting, try experimenting with different variable types and functions to reinforce your knowledge!