JavaScript Scopes Hoisting
Scopes - Hoisting
Variable :
JavaScript interpreter follows the process called hoisting.
Hoisting means all the variable and function declarations wherever they are present throughout our program, get lifted and declared to the top of the program, in case of global scope, and on top of the function declaration in case of function/local scope.
Well, remember, only the declaration and not the initialization gets hoisted to the top.
Example: Trying to access the variable without declaration:
As expected, the interpreter is unable to find the declaration of the variable 'firstName' anywhere inside the code.
Thus, the reference error is thrown.
Let us now declare and initialize the variable in the code but after it is accessed.
Because of hoisting, the code is interpreted like this by the interpreter.
Hoisting here helps interpreter to find the declaration at the top of the program and thus reference error goes away.
But interpreter says that variable is not defined. This is because hoisting only lifted the variable declaration on the top and not initialization.
Let us now understand the function hoisting with an example:
First, let us try to invoke the function showName() without declaring it in the program:
As expected, the interpreter is unable to refer to any such function in the code.
Let us now declare and initialize the function but after the statement which uses it.
Well, the reference error goes away and interpreter now executes the function.
Here, function hoisting helped interpreter find the declaration of the function at the top.
Scope Resolution :
When we write some lines of code in JavaScript, JavaScript engine interprets our code line by line and resolves the scopes of variables and functions using the lexical scoping. This means that the JavaScript code executes as per the scopes that we define in the code.
Let us understand the line by line execution considering the below example.
Step 3 is invocation of executeMe(). When invoked, the lines written inside function execute one by one as shown below: