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.

javascript  Hoisting Example declare and initialize the variable

Because of hoisting, the code is interpreted like this by the interpreter.

JS Hoisting Example

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:

javascript showName()

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.

javascript showName() example

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.

javascript Scope Resolution example

Step 3 is invocation of executeMe(). When invoked, the lines written inside function execute one by one as shown below:

javascript Scope Resolution example 2
#Scopes_Hoisting_in_Javascript #javascript_hoisting #variable_hoisting_in_javascript #javascript_function_hoisting #variable_hoisting_javascript #javascript_variable_hoisting

(New page will open, for Comment)

Not yet commented...