Like many other programming languages, JavaScript also has variables. Variables can be thought of as named containers. Data can be placed in these containers and the data can be referred simply by naming the container.

Before using a variable in a JavaScript program, it must first be declared. Variables can be declared in javascript with the var keyword as follows:

<script type="text/javascript">
      var money;
      var name;

Multiple variables can also be declared with the same var keyword as follows:

<script type="text/javascript">
      var money, name;

Rules for JavaScript variables:

Reserved keywords cannot be used as javascript variable names. For example, break or boolean variable names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.

JavaScript variable names are case-sensitive. For example, Name and name are two different variables.
JavaScript variables have only two scopes.

  •   Global Variables − A global variable has global scope which means it can be defined anywhere in our JavaScript code.
  •   Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable with the same name. Whenever a local variable or a function parameter with the same name is declared it effectively replaces the value of the global variable. Taking a look at the example below:


      <script type = "text/javascript">
            var myVar = "global"; // Declare a global variable
            checkscope( ); 
            function checkscope( ) {
               var myVar = "local";  // Declare a local variable
               document.write(myVar); // displays local
             document.write(myVar); // displays global


local global