A variable contains a value. When you use the variable, you refer to the data it represents. You use variables to store, retrieve and manipulate values in your code.
// A single declaration.
// Multiple declarations with a single var keyword.
var x, y, z;
// Variable declaration and initialization in one statement.
var x = 0, y = 100;
var z = 234;
var x = 5;
var y = 6;
// Let's do some calculation.
z = y * x;
document.getElementById("variablesdemo").innerHTML = "The value of z is: " + z;
- It's required to use an ASCII letter as the first character, it can be either an uppercase or a lowercase. It must comply with Unicode variable naming conventions or it can be an underscore (_) character. Note that a number cannot be used as the first character.
- All subsequent characters must be either letters, numbers, or underscores (_).
- The variable name cannot be a reserved word.
Example of legal variable names:
Example of illegal variable names:
// Cannot begin with a number.
// The ampersand (&) character is not a valid character for variable names.
var Old & Dog
var x = null;
var y = 3 * x; // y = 0
// y will have the value NaN because x is undefined.
var y = 1 * x;
// Result: NaN
// Here the variable x is declared implicitly.
x = "";
// This will return an empty result.
// This will cause an error since the variables are not declared and do not exist.
var x = a * b;
var x = 2000;
var y = "Hello";
// The number is coerced to a string.
x = x + y;