hoisting
Introduction
Hoisting is a Javascript mechanism where variables and function declarations are moved to the top of their scope during the compilation phase.
This guide explains hoisting in depth and it will no longer be a confusing topic for you!
Before, make sure you understand what a scope is. We have article about it: Scope in Javascript
What is hoisting?
Hoisting allows you to use functions and variables before they are declared.
In Javascript, declarations
are hoisted to the top, but assignments
are not.
If you don't know the difference between declarations and assignments we have an article about it: Declaration vs assignment
Basic example with variable hoisiting:
The declaration var x
is hoisted to the top, but the assignment x = 5
is not.
There is a slight difference about hoisting var
, let
, const
, we also have an article explaining the difference between those: Let, const and var
Function hoisting
Function declarations are hoisted entirely, allowing you to call functions before they appear in the code.
However, arrow functions
are treated as variables and are not hoisted in the same way.
With arrow functions:
Let and const hoisiting
Variables declared with let
and const
are hoisted but not initialized,
leading to a ReferenceError
if accessed before their declaration.
Class Hoisting
Similar to let
and const
classes are hoisted but not initialized.
Hoisting in closures
The inner function is hoisted within the outer function, allowing it to be called before its declaration.