During pair code-reviewing at work, I learned from my coworker about JavaScript hoisting. Our code was using a function but the declaration of the function was actually below the usage line. He referred to this as ‘hoisting’ and I got curious to know more about it.
Definition of Hoisting
According to the MDN web docs, Javascript hoisting refers to “the process whereby the interpreter appears to move the declaration of functions, variables, or classes to the top of their scope, prior to execution of the code.”
Behaviour of Hoisting
- value hoisting: Being able to use a variable’s value in its scope before the line it is declared
- declaration hoisting: being able to reference a variable in its scope before the line it is declared.
- Declaration of the variable causes behaviour changes in its scope before the line in which it is declared.
Temporal Dead Zone
A let
or const
variable is said to be in a “temporal dead zone” from the start of the block until code execution reaches the line where the variable is declared and initialized. (let
allows you to declare variables that are limited to the scope of a block statement).
Temporal Dead Zone can cause observable changes in scope:
const x = 1;
{
console.log(x); // ReferenceError
const x = 2;
}