Hoisting

What is it? Restrictions? Benefits?

“Hoisting” is a term used to define the order in which function and variable declarations can be stored in memory, then executed.

JavaScript code runs in two phases, the compilation phase (1), and the execution phase (2). Function and variable declaration take place during the compile phase, then are executed during the execution phase… pretty simple, right?

Example 1

Now what if I told you you could call the function ‘saySomething’ before you declare it, like this.

Example 2

This is an example of hoisting. Example 1 doesn’t show the two phases that js code runs in, Example 2 on the other hand, is a little more interesting. JavaScript always compiles the code first then goes back through the code and executes everything that needs to be done.

Restrictions

Even though js runs in two phases, there are still some limitations to what can be hoisted and what can’t be. In the two examples above, the functions are both declared with the general syntax of ‘function name(params)’, but there are multiple ways to declare a function, lets dive in on that.

Example 3

Function sayAnything() is defined with the arrow function syntax ‘const name = () => {}’. The output of example’s 1, 2, and 3 are all the same, but if we try and hoist the execution of example 3, we get and error.

Example 4

Arrow functions can’t be hoisted because of lexical declaring. Introduced in ES6 were two new ways of declaring variables using ‘let’ and ‘const’. Both ‘let’ and ‘const’ do not allow for hoisting, in turn, not allowing for arrow functions to be hoisted as they are declared with the ‘const’ keyword.

Example 5
Example 6

5 and 6 are examples of the restriction on hoisting. A lexical declaration error will be issued when you try and run these two code blocks.

Benefits… Sort of

JavaScript has no set format in which code has to be written, so, hoisting can benefit readability with code.

Calling all functions in a certain are of your code can provide an easier way to see what is going on… all this is completely based on preference though. Hoisting does not benefit or is not a detriment to the functionality of your code.

Software Engineer | Athlete | Formula One Enthusiast