Monday, 21 September 2015

JavaScript Variable

JavaScript Variable
JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
  1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
  2. After first letter we can use digits (0 to 9), for example value1.
  3. JavaScript variables are case sensitive, for example x and X are different variables.

Correct JavaScript variables

  1. var x = 10;  
  2. var _value="sonoo";  

Incorrect JavaScript variables

  1. var  123=30;  
  2. var *aa=320;  

Example of JavaScript variable

Let’s see a simple example of JavaScript variable.
  1. <script>  
  2. var x = 10;  
  3. var y = 20;  
  4. var z=x+y;  
  5. document.write(z);  
  6. </script>  

Output of the above example

30

JavaScript local variable

A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. For example:
  1. <script>  
  2. function abc(){  
  3. var x=10;//local variable  
  4. }  
  5. </script>  
Or,
  1. <script>  
  2. If(10<13){  
  3. var y=20;//JavaScript local variable  
  4. }  
  5. </script>  

JavaScript global variable

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. For example:

  1. <script>  
  2. var data=200;//gloabal variable  
  3. function a(){  
  4. document.writeln(data);  
  5. }  
  6. function b(){  
  7. document.writeln(data);  
  8. }  
  9. a();//calling JavaScript function  
  10. b();  
  11. </script>  

No comments:

Post a Comment