JavaScript Variables

Variable means anything that can vary.In JavaScript , variable is  name of storage location whose value vary according to query or input by user.

Rules to declare JavaScript variable

  1. Variables can be declare using var keyword.
  2. Variable name are case sensitive. means data,Data, DATA have different meaning.
  3. variables name can’t be start with digits(0-9).
  4. variables name can contain letters, digits,symbol $ and_.
  5. variable can’t be reserve keyword e.g. var , function , script etc.

Variable Declaration and Assigning Value

Syntax:-

var <variable-name>;

var <variable-name>=<variable-value>;

Declaration of Variable

var a1;

var test;

var TEST;

In above example we declare three variables named a1 , test , TEST. We does not assign any value and the default value of variable is undefined.

Initialization of Variable

After declaring ,we can assign value to variable by using ‘=’ operator.

var a1;             //declare

var a1=100;         //assigning value

var test;           //declare

var test='Hello';   //assigning value

var TEST=1000;      //declare and assignment

In above example variables a1 and test declare first and then assigned value.Variable named TEST declare and assigned integer value in single line.

In JavaScript you need not to declare data type of variable.You can assign any literal value to variable.

var s;

s="this is a string variable"//assigning a string value

alert(s);//access a variable

var v1=500; //declaring as well as initializing an integer value.

alert(v1);

In above example we declare variable a and assigned it a string value ,so it will became a string variable.Similarly assigned integer value to v1 and it will be a integer variable. This is the reason it is called as loosely-typed variable unlike Java and C++ where type of variable must declare before using it.

Multiple Variable Declaration

var a1=100,b1="text",c1;

We can declare multiple variable in single line.

Scope Of Variable

In JavaScript variables can be declare in two scopes:-

          1.  Local variable

          2. Global variable

Local Variables:- Local variable is declared inside the block or function and accessible inside that particular block.

<script>  
function test(){  
var a=5;//local variable  
}  
</script>

Global Variable:- Global variables are declared globally , outside any function. It can be accessed from any where and can be call within any function.

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

Back                                                                                                                                             Next