Hoisting

Ok so this is going to be a short one. I recently stumbled upon a question in StackOverflow (actually include a link here) that was asking something like this:

Why is this code valid?

//Start of this file
myFavoriteMovie = "Star Wars"
console.log(myFavoriteMovie);   //Actually prints 'Star Wars' even though `myFavoriteMovie` is undeclared
.
.
.
// A few more lines of irrelevant code
.
.
.
var myFavoriteMovie = "Inception";   //myFavoiteMovie declared
console.log(myFavoriteMovie);

So what do you think would be the output of this script?
Most people would say that an error will be shown claiming that `myFavoriteMovie` is undefined or that `undefined` will be printed in the console. The strange thing is, that the same people that find this code wrong, will find the following code fine:

var game = new VideoGame("Mass Effect", "Bioware", "Action RPG");
console.log(game);

function VideoGame(title, developer, genre){
	this.title = title;
    this.developer = developer;
    this.genre = genre;
}

Those two examples are essentially the same thing. In the first example, `myFavoriteMovie` is used before declaration. In the second example, the same thing happens with the VideoGame function. It’s used before declaration but few people notice the similarity. I too, could not see it and I was surprised when I found out. I think the source of confusion for most of us is that using a variable before declaration is counterintuitive, it’s something that we normally do not do and if we do it’s probably by mistake. However, defining a function or a class at the end of a file and using it before declaring it is rather common because it helps some developers (including me) with code organization. But using a variable before declaring seems off to the most of us. Perhaps that’s because most of us started coding in a more strict language than JavaScript, C for example where it is unthinkable to use a variable before declaring it.

Anyway, there is a name for this and that’s Hoisting. It’s something that happens every time you run your JavaScript script (or just JavaScript 😛 ). Hoisting is the process of moving all variable, function and class declarations found in the file, at the start of that file. So right before execution the code of the first example gets transformed and ends up looking like this :

var myFavoriteMovie = "Inception";
myFavoriteMovie = "Star Wars";
Console.log(myFavoriteMovie);
.
.
.
// A few more lines of irrelevant code
.
.
.
myFavoriteMovie = "Inception";
console.log(myFavoriteMovie);

That is why you can use variables, functions, classes and objects before you actually declare them.

Hope you find this explanation of JavaScript Hoisting helpful. Check more awesome JavaScript stuff here

Leave a Reply

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