JavaScript: Hoisting, Variable shadowing, Scope and Closures
What actually JavaScript is?
It is a programming language used primarily by Web browsers to create a dynamic and interactive experience for the user. Most of the functions and applications that make the Internet indispensable to modern life are coded in some form of JavaScript.
Now let’s check about the other above mentioned terms in detail.
Hoisting in JS(JavaScript):
Hoisting is a Js mechanism where variables and function declarations are moved to the top of their scope before code executes. This part is done when the program is being compiled (before the execution part).
Variable Shadowing:
In programming languages, variable shadowing occurs when a variable is declared in certain scope has the same name defined on it’s outer scope. And when we call the variable from the inner scope, the value mentioned in inner scope will be taken into account.
Here is an example for the variable shadowing.
In the above code, we’ve declared two different values for a same variable “a”. Since, variable “a” was declared with a new value inside myFunc(), system will fetch that value for any operations performed inside that particular scope irrespective of global value.
This is called as “Variable Shadowing”.
Scope:
In JS there are two types of scope:
- Local scope
- Global scope
-Variables defined outside a function are called global variables.
-Variables defined within a function are local variables.
Closures:
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JS, closures are created every time a function is created, at function creation time.
To use a closure, define a function inside another function and expose it.
The inner function will have access to the variables in the outer function scope, even after the outer function has returned.
Hope you were able to get an idea about JS mechanism!