JavaScript Variable Scopes
Variable Scopes :
Variable declaration in the JavaScript program can be done within the function or outside the function. But the accessibility of the variable to other parts of the same program is decided based on the place of its declaration.
This accessibility of a variable is referred to as scope.
JavaScript scopes can be of three types:
Let us get a better understanding of scopes with the help of an example.
Example :
Demo :
var keyword :
If we declare a local variable without the use of keyword 'var', it takes a global scope.
Observe the change in output, if we remove the 'var' keyword from local variable 'lastName' in the previous example:
As observed, without the use of keyword 'var', local scope changes to the global scope. Thus, it re-initializes the variable 'lastName' to the new value 'Zuckerberg'. Now wherever the variable 'lastName' is used throughout the page, the new value is displayed.
Tip: Use keyword 'var' when declaring local variables to avoid the wrong interpretation by the browser.
Nested scope :
Consider a scenario where the function is nested within another container function. The local scope for container function and nested function will have different interpretations in this scenario.
A Nested function can access variables having the local scope in container function. But container function cannot access variables having local scope inside the nested function.
The local scope of the variables inside the nested function is referred to as nested scope.
Let us understand the resolution of the nested scope with the help of an example.
Let us understand the resolution of the nested scope with the help of an example.
We have added nested function designation() inside the existing function fullName().
This nested function declares a variable role that will have the nested scope.