Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope (to the top of the current script or the current function).
In JavaScript, a variable can be used before it has been declared. In many other languages, this would cause an error. JavaScript "hoists" the declaration, but not the initialization.
x = 5; // Assign 5 to x
console.log(x); // Display x
var x; // Declare x
JavaScript only hoists declarations, not initializations. If you declare and initialize a variable at the bottom, the value will be undefined when used at the top.
console.log(y); // Result: undefined
var y = 7; // Initialization is NOT hoisted
Variables defined with let and const are also hoisted to the top of
the block, but not initialized. They are in a "Temporal Dead Zone" from the
start of the block until the declaration is processed.
let or const variable
before it is declared will result in a ReferenceError, helping you find potential bugs
early!
Function declarations are hoisted completely. This means you can call a function before you define it in your code.
hello(); // Works!
function hello() {
console.log("Hello World!");
}
Note: Function expressions (where a function is assigned to a variable) are not hoisted because they follow variable hoisting rules.
var hoists as undefinedlet/const hoist but cause error if used early
(Temporal Dead Zone)