JavaScript Variable Scopes

Variable Scopes :

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:

javascript types of variable scope
javascript syntax of variable scope

Let us get a better understanding of scopes with the help of an example.

Example :

javascript global variable

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:

javascript global variable 2

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.

Notepad

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.

Nested scope syntax

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.

javascript variable with global scope
#Variable_Scopes_in_Javascript #declare_global_variable_in_javascript #javascript_local_variable #local_and_global_variables_in_javascript #define_global_variable_in_javascript #javascript_set_global_variable #javascript_declare_global_variable #javascript_nested_variable #Nested_scope

(New page will open, for Comment)

Not yet commented...