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

image

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:

image

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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s