ENOTES

Local and global variable in JavaScript

access_time Feb 23, 2022 remove_red_eye 8779

Variables are the identifiers which holds value during our program execution. These values may change throughout the program. Depending upon the nature of data variable can hold several type of value. The type of value stored in the variable are denoted by datatype. There are two types of datatypes used in JS.

Data types used in JavaScript

a) Primitive data type: They are inbuilt datatype used in JS

Data TypesFunction
NumberIt represent numeric value i.e. integer and floating number. We can use BigInt to represent number with large value.
StringIt represent alphanumeric values i.e. text
BooleanIt represent either true or false value.
Null It represent empty or unknown value.
Undefined If variable is declared but the value is not assigned then the variable is of undefined type.

b) Non-Primitive datatype: They are the derived datatypes from primitive datatype.

Data TypesFunction
Array It store multiple values of same type under a same name.
Object  It has methods and properties.

Variables in JavaScript

Variables in JavaScript are declared by using keyword 'var'. for eg,
var a=3,b=4;
var fruit = "apple";

Types of variable in JavaScript

a) Local variable 
Those variable which are declared inside the block or function is called local variable. Local variable can only be accessed and used within the block or function.

<HTML>
<HEAD><TITLE>sample</TITLE></HEAD>
<BODY>
<BUTTON onclick = "disp()">Click me</BUTTON>
<SCRIPT>
function disp()
{
var a=5;
document.write(a);
}
</SCRIPT>
</BODY>
</HTML>

In above example, the variable 'a' is declared inside the function disp(). So, it can be used only within the function block. Other function or block cannot use the value of 'a'. Hence, to overcome this limitation we have global variable.

b) Global variable
Those variable which are declared outside the block or function is called global variable. Global variable can  be accessed and used within any other function or the block.

<HTML>
<HEAD><TITLE>sample</TITLE></HEAD>
<BODY>
<BUTTON onclick = "disp()">Click me</BUTTON>
<BUTTON onclick = "cisp()">Push me</BUTTON>
<SCRIPT>
var a=5;
function disp()
{
document.write(a);
}
function cisp()
{
document.write(a);
}
</SCRIPT>
</BODY>
</HTML>

In above example, the variable 'a' is declared outside the two function disp() and cisp(). So, it can be used by both function block. When user press Click me then, disp() function is called, this function will display the value of 'a' i.e. 5 which is declared outside of the function. Similarly, when user press Push me then, cisp() function is called, this function will also display the value of 'a' i.e. 5. This is because variable ‘a’ is declared outside of function or block which can be used by any number of function or block.
Note: Block represent the statement written inside curly bracket { }