Hoisting, where to declare variables

Andrew Park
2 min readMay 2, 2021

Rule of thumb is all variables (const, let) must be declared before it can be used (var has slightly different rule, but we should never use var in new javaScript).

Using a variable that has not been declared causes “Uncaught ReferenceError: not defined”:

Using a variable that is declared later causes “Uncaught ReferenceError: “Cannot access before initialization”:

When both variables are declared before used, code works as expected:

And same rule applies to function expressions as well (function declaration is one exception that will be discussed later).

Below both function expressions causes “Uncaught ReferenceError: “Cannot access before initialization”:

With Arrow function:

Once the function is invoked after declared, the code works as expected:

One exception is function declaration:

In below code, Hoisting allows function fullName to be invoked before the function is declared:

Best practice is to declare all variables (cont, let) and even function declarations at the top of each scope. This will make everyone happy 🤗

--

--