Tejas Manohar


Introducing the Hoisting Dilemma!

JavaScript has always known to be weird about scope. In most C-based languages, variables are instantiated where they are declared. However, with JS, standard variable declarations are moved to the top through a process known as hoisting.

Before diving deeper, let’s take a moment to establish the difference between two popular terms that are often improperly interchanged by beginner developers — declaration and initialization.


var x;


x = 5;

Now that this is out of the way, let’s talk about what you’re really here for… hoisting! In the example below, we use the variable x before it has been declared. This is an example of JavaScript’s hoisting.

x = 7; // Assign 7 to x
var x; // Declare x
console.log(x); // => 7

Simple enough? Well, hoisting isn’t as consistent as you’d expect at first.

var z = 3; 
(function() {
console.log(z); // => undefined
var z = 4;
Undefined? But before! Wha! Huh?

Yup! undefined indeed. Even though the local variable z was automatically hoisted to the top of function scope (above the log statement) as expected, its value was still not defined before the log statement’s execution since only declarations are hoisted in JavaScript, not initializations.

Now you see why this can be confusing and promote creating simple errors unconsciously! But don’t worry, we can easily work around this.

The moral of the story (pre-ES2015, another article coming soon) is to just keep things simple by declaring all variables at the top.

If you found this interesting, consider following me on Twitter and GitHub, where I share cool code amongst other things.

More by Tejas Manohar

Topics of interest

More Related Stories