JavaScript runs code in two main steps:
var
,
let
, and
const
variables.
var
to
undefined
.
let
and
const
as unusable until their declaration (this is the
Temporal Dead Zone
).
Hoisting is when JavaScript prepares all variable and function declarations before running the code, so they can be used earlier in their scope. It doesn't actually move the code but sets them up in memory.
For
var
, the variable is set to
undefined
until its value is assigned. For
let
and
const
, you can't use them before their declaration line (they're in the
Temporal Dead Zone
).
Function declarations are fully ready to use anywhere, but function expressions (like
var x = function() {}
) aren't usable until assigned.
This function works before it's defined because function declarations are fully hoisted.
hi(); // Output: Hello
function hi() {
console.log("Hello");
}
This function does not work before it's defined because function expressions are not hoisted.
hi(); // Error: Cannot access 'hi' before initialization
const hi = function () {
console.log("Hello");
};
hi(); // Output: Hello
Variables with
let
or
const
are set up in memory but can't be used until their declaration line. This waiting period is called the
Temporal Dead Zone (TDZ). Trying to use them early causes an error.
console.log(x); // ReferenceError: Cannot access 'x' before initialization let x = 10;