A JavaScript variable is simply a name of a storage location. There are two types of variables in JavaScript:
- Local variable
- Global variable
There are some rules for declaring a JavaScript variable:
- Name
must begin with a letter (a-z or A-Z), underscore ( _ ), or dollar( $ ).
- After first letter digits (0-9) can be used to construct a variable name.
- JavaScript variable names are case sensitive e.g., tea, Tea and TEA are different variables.
- No reserve word must be used as a variable name.
JavaScript local variable
A local variable is declared inside a block { } or function. It is accessible within the function or the block only. If you try to access it from outside, it will throw you an error.
For example:
1 2 3 4 5 6 7 8 9 10 11 | <script> function JS() { var a = 79; //local variable } </script> OR, <script> If(10 < 13) { var z = 20; //JavaScript local variable } </script> |
JavaScript global variable
A global variable is accessible from anywhere within the script. A global variable must be declared outside the function or declared with window object is.
Consider the example below:
1 2 3 4 5 6 7 8 9 10 11 12 | <script> var data = 500; //gloabal variable function a() { document.writeln(data); } function b() { document.writeln(data); } a(); //calling JavaScript function (no error) b(); </script> |
Variable Declaration and Initialization
JavaScript variable must be declared using the var or let keyword.
var one = 1; // variable stores numeric value 1
var two = ‘two’; // variable named ‘two’ stores string value ‘two’
var three; // declared a variable named ‘three’ withoutassigning a value
let num1=23; //num1 stores numeric value 23
Multiple variables can be declared in a single line:
var one = 1, two = ‘two’, three;
JavaScript also allows variable declaration without the keyword var. In that case, a value must be assigned while declaring a variable.
one = 1;
two = ‘two’;