Javascript hoisting1 min read

Ever heard about hoisting in Javascript?
Yep, you surely did… But what the heck is hoisting and how to handle it? Let’s see…

HOISTING PRELUDE ?

I probably guess that most of you know how Javascript interpreter works! But for you who don’t, let’s take a quick reminder.

During Javascript code execution, interpreter runs twice.
First time when it runs through the code, it makes safety checks (syntax checking etc) and small optimizations.
This compile run is also the time when hoisting occurs.
The second time when interpreter runs it executes our code line by line.

HOISTING, WHAT IS ALL ABOUT?

Hoisting is moving function declarations to the top of the current scope / function.
Since in Javascript variable can be used before it has been declared, Javascript during the first run, hoists declarations but not initializations!
Let’s see two examples with different results:

Example 1:

var foo = "hello"; 
var bar = "world" ; 
console.log( foo + " " + bar); //  "hello world"

Example 2:

var foo = "hello"; 
console.log( foo + " " + bar); //  "hello undefined"
var bar = "world";

In Example 2 as we can see, bar variable is declared because of the hoisting but no initial value is available to this variable.
That’s becuase initializations are not hoisted.

How interpreter sees it is like this:

var foo = "hello"; 
var bar;
console.log( foo + " " + bar); //  "hello undefined"
bar = "world";

SUMMARY:

As you can see, hoisting is an interesting Javascript feature 🙂 which might cause bugs for most of developers.
So, it’s necessary for a Javascript developer to understand hoisting and avoid potential bugs.
In order to avoid these kinds of bugs you might use ‘use strict’, which prevents variable to be used unless they are declared.

Leave a Reply

Your email address will not be published. Required fields are marked *