Variable Hoisting in Javascript

To hoist is to raise, to lift up according to the Merriam Webster dictionary. When I first encountered the term JavaScript Hoisting I thought that it should raise up something but I did not know what. Now I know and I would like to share it with you. JavaScript has the ability to hoist variables that is to say to lift them to the top of a particular scope.

var myName = “Gustavo” 

This is actually read by JavaScript as:

var myName;
myName = “Gustavo” 

“var myName;” is declared on top of the current scope. its assignment occurring afterwards at its original place. If you had run the first code you would get the console to print “undefined” rather than an error because of the variable declaration that was hoisted.

Because of this quirky behavior it is good practice to declare and assign your variables first.

var myName = “Gustavo”;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s