var <variable-name>; var <variable-name> = <value>;
var one = 1; // variable stores numeric value var two = 'two'; // variable stores string value var three; // declared a variable without assigning a value
In the above example, we have declared three variables using var keyword: one, two and three. We have assigned values to variables one and two at the same time when we declared it, whereas variable three is declared but does not hold any value yet, so it's value will be 'undefined'.
Declare Variables in a Single Line
Multiple variables can also be declared in a single line separated by comma.
var one = 1, two = 'two', three;
Declare a Variable without var Keyword
one = 1; two = 'two';
Scope of the variables declared without var keyword become global irrespective of where it is declared. Global variables can be accessed from anywhere in the web page. Visit Scope for more information.
var one = 1, two = "two"
Please note that semicolon is optional.
C# or Java has strongly typed variables. It means variable must be declared with a particular data type, which tells what type of data the variable will hold.
var one =1; // numeric value one = 'one'; // string value one= 1.1; // decimal value one = true; // Boolean value one = null; // null value
- Variable stores a single data value that can be changed later.
- Variables can be defined using var keyword. Variables defined without var keyword become global variables.
- Variables must be initialized before using.
- Multiple variables can be defined in a single line. e.g. var one = 1, two = 2, three = "three";