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:
- Declaration of variable
- 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:
Leave a Reply