/    /  Javascript-Variables

Javascript-Variables

 

A JavaScript variable is simply known as the storage location. There are two types of variables in local variable and global variable.

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

  • The name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
  • After the first letter, we can use the digits 0 to 9.
  • JavaScript variables are case sensitive( x and X are different variables).

 

Example :

 

<html>
<body>
<script>  
var x = 10; 
var y = 70; 
var z=x+y; 
document.write(z); 
</script> 
</body>
</html>

 

OUTPUT:

 

80

 

local variable :

 

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

 

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

 

OR

 

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

 

global variable:

 

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

 

Example:

 

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

</script> 
</body>
</html>

 

OUTPUT:

 

500 500