JavaScript Variables

JavaScript variables are named containers for storing data values.

It uses reserved keyword var to declare a variable.

There are some rules while declaring a JavaScript variable:

1. Name must start with an alphabet (a to z or A to Z), underscore ( _ ), or a dollar( $ ) sign.

2. After first letter we can use digits (0 to 9) as well.

3. JavaScript reserved keywords can’t be used for naming variables.

4. Variable names are case sensitive.

Examples of some correct JavaScript variables,

abhi, _abc12;

Examples of some incorrect JavaScript variables,

12abc, %xyz;

There are two types of variables in JavaScript:

1. Local Variables: JavaScript local variables are declared inside the functions or some block of code. They are accessible only within that function or block of code.

2. Global Variables: JavaScript global variables are declared outside the functions or block of code. They are accessible from any function or block of code.

Note: Within the body of a function, a local variable takes precedence over a global variable with the same name.


    var g = 100; //global variable
    var c = 10; //global variable
    function func()
        var c = 50; //local variable
        document.writeln(g); //prints value of global variable i.e. 100
        document.writeln(c); //prints value of local variable i.e. 50