Hoisting
# Hoisting
# What is hoisting?
hoist /hoist/ - verb: raise (something) by means of ropes and pulleys.
Hoisting is a behavior in JavaScript where variable and function declarations are moved, or "hoisted", to the top of their containing scope during compilation.
When we look at var a = 2
, we tend to think of it as one statement. But the JavaScript engine does not see it that way. It sees var a
and a = 2
as two separate statements, the first one a compiler-phase task, and the second one an execution-phase task.
This means, all function and variable declarations in a scope are processed first before the code itself is executed.
# let
and const
Variables declared with let
and const
are also hoisted, but they remain in a temporal dead zone (TDZ) from the start of the block until the declaration is encountered. Accessing them in this zone would result in a ReferenceError
.
console.log(myVar); // Reference Error
let myVar = 1;
console.log(myVar); // 1
But if we declare the variable with var
, the variable will be initialized with undefined
.
console.log(myVar); // undefined
var myVar = 1;
console.log(myVar); // 1
The best practice is to use let
and const
over var
to reduce the risks associated with hoisting.
# Function hoisting
Unlike variables, both the function declarations and the function body are hoisted.
console.log(myFunction()); // Output: "Hello"
function myFunction() {
return "Hello";
}
Function expressions (named or anonymous) are not hoisted.
console.log(myFuncExp); // Output: undefined
console.log(myFuncExp()); // Output: TypeError
var myFuncExp = function () {
return "Hello";
};