JavaScript variable

Variables are useful way to store information. A variable is a name given to the storage location. There could be two types of variables available in JavaScript.

  • Local Variable
  • Global Variable

Rules for JavaScript Variable

There are various types of rules when we declare a variable in JavaScript. The rules are also known as identifiers. Following are the rules for declaring a variable.

  • The name of a variable must start with a letter ranging from a to z or A to Z.
  • Variable is case sensitive. A and a are two different variable.
  • One can even use (_)- Underscore and ($)- Dollar sign as a variable.
  • After using an alphabet, you can use numbers like from 0-9. Example- a1, b2, c3, x1 etc.
Note :- JavaScript identifiers are case-sensitive. And JavaScript variables are containers for storing data values.

Correct and Incorrect Variable Declaration in JavaScript

Below is the correct usage of variable


var a =50;
var $="new";

 

Incorrect usage includes following examples:

    var  23=30;  
    var *xx=420;  

Example to define JavaScript Variable

Let’s have a look at a basic example to define a JavaScript variable.

<script>
var x = 20;
var y = 50;
var z=x+y;
document.write(z);
</script>

The output of above program is 70

Local variable and Global Variable

A local variable is defined inside the function and accessible only for that particular function only. This is similar to the C language variable declaration.

<script> 
    function xyz(){  
    var a=10;//this is a local variable  
    }  
    </script>

Another example of above declaration is by using

<script> 
    If(10<13){  
    var c=20;//another example of local variable  
    }  
     </script>

On the other hand, a global variable could be defined at the start of the function or defined in the global function when the code is started. This way the global variable could be called in any function and its value could be used many times.

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