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.

  var x = 100;  

  var _value=“abhi”;  

Incorrect JavaScript variables

  var  321=69;  

  var *tt=392;

Example of JavaScript variable

Let’s see a simple example of JavaScript variable.

  <script>  

  var a = 10;  

  var b = 20;  

  var c=a+b;  

  document.write(c);  

  </script>  

JavaScript local variable

A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. For example:

 

      <script>  

      function abc()

     {  

      var x=10;//local variable  

      }  

     </script>  

Or,

 

        <script>  

       If(10<13){  

       var y=20;//JavaScript local variable  

       }  

     </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:

  <script>  

  var data=200;//gloabal variable  

  function a()

  {  

      document.writeln(data);  

  }  

 function b()

 {  

     document.writeln(data);  

  }  

  a();//calling JavaScript function  

  b();  

  </script>  

JavaScript Global Variable

JavaScript global variable is declared outside the function or declared with window object. It can be accessed from any function.

Let’s see the simple example of global variable in JavaScript.

   <script>  

   var value=50;//global variable  

   function a()

   {  

    alert(value);  

    }  

   function b()

    {  

   alert(value);  

     }  

    </script>  

Declaring JavaScript global variable within function

To declare JavaScript global variables inside function, you need to use window object. For example:

 
         window.value=90;  

 

Now it can be declared inside any function and can be accessed from any function. For example:

     function m(){  

    window.value=100;   //declaring global variable by window object  

      }  

      function n()

     {  

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

     }  

 Internals of global variable in JavaScript

When you declare a variable outside the function, it is added in the window object internally. You can access it through window object also. For example:

 

    var value=50;  

    function a()

   {  

    alert(window.value);//accessing global variable   

    }