JavaScript Variable


A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript :

  • local variable
  • global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

  • All JavaScript variables must be identified with unique names.
  • These unique names are called identifiers.
  • Identifiers can be short names (like x and y), or more descriptive names (age, sum, totalVolume).
  • The general rules for constructing names for variables (unique identifiers) are:
    • Names can contain letters, digits, underscores, and dollar signs.
    • Names must begin with a letter
    • Names can also begin with $ and _ (but we will not use it in this tutorial)
    • Names are case sensitive (y and Y are different variables)
    • Reserved words (like JavaScript keywords) cannot be used as names
Correct JavaScript variables
var x = 20;
var _value="soon";
Incorrect JavaScript variables
var  203=20;
var *bb=420;

Example

<script type="text/javascript">
var a = 20;
var b = 40;
var x=a+b;
document.write(x);
</script>
Output
60

JavaScript local variable

JavaScript local variable is declared inside block or function. It is accessible within the function or block only.

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

JavaScript global variable

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

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

Share this article on