JS Variable

In simple, JavaScript variable is a name of storage location. There are two types of variables in JavaScript :

  • Local variable
  • Global variable.

 

All JavaScript variables must be identified with unique names. These unique names are called identifiers (There are some rules while declaring a JavaScript variable, known as identifiers).

Identifiers can be short names (like x and y) or more descriptive names (total, sum, id).

Rules for constructing names for JavaScripts Variables

  • Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
  • After first letter we can use digits (0 to 9), for example: value1.
  • JavaScript variables are case sensitive, for example x and X are different variables.
  • Reserved words (like JavaScript keywords) cannot be used as names.

 

Correct JavaScript variables

<script>
var x = 5;  
var _value="Uttarakhand";
</script> 

Incorrect JavaScript variables

<script>
var  123=50;  
var *aa=Academe;
</script> 

Note: JavaScript identifiers are case-sensitive.

 

Example of JavaScript variable:

<script>
var box1 = "Uttarakhand";
var box2 = " Academe";
var mainBox = box1 + box2;
document.getElementById("demo").innerHTML ="The main Box value is: " + mainBox;
</script>

Output:

 

 

A JavaScript local variable is declared inside block or function. The function or block is only accessible.

For Example:

<script>
function abc(){ 
var x=10; //local variable
} 
</script>

or,

<script>
If(10<15){ 
var y=50; //JavaScript local variable
} 
</script>

A JavaScript global variable is accessible from any function. A variable i.e. The declared global variable is known outside the function or with a window object.

For Example:

<script>
var data="UK Academe";//gloabal variable 
function a(){ 
document.writeln(data);
} 
function b(){ 
document.writeln(data); 
} 
a(); //calling JavaScript function 
b();
</script>

Output:

 

To declare JavaScript global variables inside function, we need to use window object.

window.value=90;

It can now be declared and accessed from any function in any function.

<html>
<body>
<button onclick="n()">Click me</button>

<script> 
function m(){  
window.value=500; //declaring global variable by window object  
}  
function n(){  
alert(window.value);//accessing global variable from other function  
}
m();
</script> 

</body>
</html>  

Output:

 

When we declare a variable outside the function, it is added in the window object internally. We can access it through window object also.

For Example:

<script>
var value=50;
function a(){
alert(window.value); //accessing global variable
}
</script>