JavaScript Variables

JavaScript variables provide a way to catch and hold values. A variable may take different take values at different times during execution. A variable name can be chosen in a meaningful way so as to reflect its function or nature in the program. Some example of such variable names are:

Example:

var height;
var sum;
var name;

the special word(keyword) var indicates that this sentence is going to define a variable. Variable names may consist of letters, digits, and the underscore(_) character, subject to the following conditions:

  • They must start with a letter(a-z or A-Z) or undrscore(_) or dollar($) sign.
  • Uppercase and lowercase are significant. That is, the variable Sum is not the same as total or TOTAL.
  • It should not be a keyword.
  • White space is not allowed.

To store a value in a variable is called variable initialization. You can store a value anytime in a variable after declaring the variable. Example of variable initialization:

Example:

var num1 = 5;
var num2 = 10;
var num3;
num3 = 7;



JavaScript Variable Scope

The variable scope depends on where the variable is defined. There are two scopes of JavaScript variables:

  • Global variables - It is accessible from anywhere in the code.
  • Local variables - It is accessible only within the function where it is declared.

Here is an example of global variable:

Example:

<script type="text/javascript">
var num2 = 10;
function jsexample() {
document.write(num2);
}
jsexample();
</script>

Run Example

Here is an example of local variable:

Example:

<script type="text/javascript">
function jsexample() {
var num2 = 10;
document.write(num2);
}
jsexample();
</script>

Run Example