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.
a) Primitive data type: They are inbuilt datatype used in JS
Data Types | Function |
Number | It represent numeric value i.e. integer and floating number. We can use BigInt to represent number with large value. |
String | It represent alphanumeric values i.e. text |
Boolean | It 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 Types | Function |
Array | It store multiple values of same type under a same name. |
Object | It has methods and properties. |
Variables in JavaScript are declared by using keyword 'var'. for eg,
var a=3,b=4;
var fruit = "apple";
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 { }