Hoisting
🚀Hoisting
is JavaScript's behavior of moving variable and function declarations to the top of their containing scope during the compile phase, before the code has been executed. This concept can lead to some surprising results in your code.
var
In JavaScript, variables declared with var
are hoisted to the top of their function or global scope, but their initialization (value assignment) is not.
// Example 1: Hoisting with var
console.log(myVar); // undefined (hoisted declaration, but not initialized)
var myVar = 5;
console.log(myVar); // 5 (after initialization)
let
and const
Unlike var
, variables declared with let
and const
are also hoisted, but they remain in the "temporal dead zone" until the code execution reaches them. Accessing them before initialization will result in a ReferenceError
.
// Example 2: Hoisting with let and const
console.log(myLet); // ReferenceError: Cannot access 'myLet' before initialization
let myLet = 10;
console.log(myLet); // 10 (after initialization)
console.log(myConst); // ReferenceError: Cannot access 'myConst' before initialization
const myConst = 20;
console.log(myConst); // 20 (after initialization)
Function declarations are also hoisted. Unlike variables, function declarations are hoisted with both their definition and body.
// Example 3: Hoisting with function declarations
myFunction(); // "Hello, world!" (function is hoisted)
function myFunction() {
console.log("Hello, world!");
}
However, function expressions are only hoisted with their variable declaration, not the function definition. This can lead to unexpected results when you try to call a function before it's defined.
// Example 4: Hoisting with function expressions
myFunc(); // TypeError: myFunc is not a function
var myFunc = function() {
console.log("This won't work until it's defined!");
};
myFunc(); // "This won't work until it's defined!" (after initialization)
Click to see how hoisting works with variables and functions:
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!