How does variable hoisting differ between var, let, and const?
Variable hoisting behaviour differs between var
, let
, and const
in JavaScript. Here's a breakdown of how each of these declarations is hoisted:
1. var
Hoisting:
- Variables declared with
var
are hoisted to the top of their scope, known as "hoisting up". - During the hoisting phase, the variable declaration is moved to the top of the scope, while the initialization remains in place.
- The variable is assigned the value
undefined
by default until its actual assignment is encountered in the code.
Example:
var
Hoisting2. let
and const
Hoisting:
- Variables declared with
let
andconst
are hoisted as well, but there is a key difference known as the Temporal Dead Zone (TDZ). - During the hoisting phase, the variable declaration is moved to the top of the scope, just like with
var
. - However, unlike
var
, variables declared withlet
andconst
remain uninitialized in the TDZ. - Attempting to access the variable before its declaration results in a
ReferenceError
because it is in the TDZ.
Example:
let
and const
HoistingConclusion:
In summary, var
variables are hoisted to the top of their scope and initialized with a value of undefined
. On the other hand, let
and const
variables are hoisted but remain uninitialized within the TDZ, resulting in a ReferenceError
if accessed before their declaration. Therefore, it's important to be aware of the hoisting behavior while writing JavaScript code and ensure variables are declared before using them to avoid any unexpected outcomes.