Simplifying function hoisting in JavaScript

To understand function hoisting, let us start by considering the code listed below:


In any other programming language, the output here would be a reference error. However, in JavaScript you will get undefined as the output. Why? Because JavaScript hoists variables at the top of the execution context. An execution context could be the function in which a variable is declared, or a JavaScript file in which a variable is declared. So, let us rewrite the above code snippet using a function:


Here, the variable “foo” is hoisted at the top of function abc execution context; which means you can access foo before it is declared. To put it simply, whenever you declare a variable, the JavaScript interpreter breaks it into two statements:

  1. Declaration of variable
  2. Assignment

The declaration of a variable goes at the top of the execution context, and assignment happens where the variable is created. So the above code snippet is broken into two statements as shown in the image below:

The variable foo is hoisted at the top of the execution context of function abc, hence when you use it before its declaration, you get “undefined” as the output.

Keep in mind that a variable declared using the let statement does not get hoisted to the top of the execution context.

Now that you understand how variables are hoisted in JavaScript, let’s explore function hoisting in JavaScript. In JavaScript a function can be created in two ways:

Read full article on the Infragistics blog

Published by

Dhananjay Kumar

Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc. Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com

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