Home >>Javascript Tutorial >Javascript Variables

Javascript Variables

Javascript Variables

A variable is Simply a container which Contains Some values.
A variable in JavaScript is the name of a storage location.
There are generally two types of variables available in JavaScript:

  • Local Variable
  • Global Variable

Variable Declaration Rules: While declaring a JavaScript Variable (also referred as identifiers), there are some rules to follow.

  • Variable name must start with only a letter whether in small or Caps and underscore (_).
  • We cant use digits in the starting of a Variable.We can only use the digits (0-9) after first letter, e.g. value2.
  • The variables in JavaScript are case sensitive, e.g. x and X are two different variables.

Let's understand the correct and incorrect variables in JavaScript by these following examples:

Correct JavaScript variables

var a = 20;  
var _str="PHPTPOINT";  
var str1="PHPTPOINT";

Incorrect JavaScript variables

var  111=20;  
var *aa=350;  

Let's understand the Variables in JavaScript with these examples:

<script>  
var a = 5;  
var b = 10;  
var c=a+b;  
document.write(z);  
</script>  	

JavaScript Local variable

A local variable in Javascript is often declared inside a block or a function and it is accessible within the block and function only.

Let's understand it with these following examples:

<script>  
function demo()
{  
//local variable
var a=5;
//We can use only inside this function
alert(a);  
}  
</script> 

JavaScript Global Variable

A global Variable can be defined as the variable that can be declared outside the function or with window object. A global variable in JavaScript can be accessed from any function.

Let’s understand the global variable with these following examples: Examle 1

<script>
//global variable  
var data=10;  
function demo()
{  
document.writeln(data);  
}  

function demos()
{  
document.writeln(data);  
}  

//calling JavaScript function
demo();  
demos();  
</script>  

Examle 2

<script>
//global variable  
var data=10;  
function demo()
{  
alert("Global Variable : "+data);  
}  

//calling JavaScript function
demo();  
</script>  

Declaring a JavaScript global variable within a function

You will have to use a window object in order to declare a global variable inside a function in JavaScript.

Examle

<script>
function demo()
{  
//declaring global variable by window object  
window.value=10;
}  

function demos()
{  
//accessing global variable from other function  
alert(window.value);
} 

//call function 
demo();
demos(); 
</script>

JavaScript Global variable's Internals

A variable is added in the window object internally, once it is declared outside the function. Now, it can also be accessed through window object.

Let's take an example for this:

<script>
var value=10;  
function demo()
{  
//accessing global variable
alert(window.value);
} 
//call demo function
demo();
</script>