A variable is used in the program to store information. It could be the age of the visitor, or the name of the user. The variable stores the information and could be used again later on.
Variable Identifier Rules
- The variable is allowed to consist of letters, numbers, and underscores, but it has to begin with either a lowercase letter or an uppercase letter or an underscore, and it can’t start with the number.
- Variable name is case-sensitive.
- A variable name cannot contain spaces.
Declare a variable
var <variable-name>; // or var <variable-name> = <value>;
var x = 1;
You need to declare a variable before you can use it. You use the keyword
var and then variable name, like
x in the above example. You could initialize the value of the variable together with the declaration or you could assign a value to it later.
It is not like other programming languages that you have to specify the type of a variable when you declare it and the type couldn’t be changed afterword.
Multiple variables could be declared in one single line separated by the comma
var one, two, three = 1, 2, 3;
var, but need to assign the value directly.
one = 1; two = 2; three, four = 3, 4;
const variables in ES6
var keyword declares the variables in the scope of the function, but
const keywords introduced in ES6 extend the variable scope to the block level
The variable declared with
const keyword couldn’t be reassigned after declaration, but the variable declared with
> let A = "1" > A = "2" "2" > const B = 1; > B = 2 VM944:1 Uncaught TypeError: Assignment to constant variable. at <anonymous>:1:3