A variable must be declared before we can use it. We declare a variable by assigning a value to it. The following statements declare variables of different data types:
txt = "John, Paul, George, and Ringo";
// The value stored in txt is a string data type.
// The words inside the quotes is a string literal.
num1 = 10;
// The value in num1 is an integer data type.
num2 = 1.23456
// The value in num2 is a floating point data type.
oyes = true;
// The value stored in oyes is a Boolean type.
We cannot use a variable that has never been declared, as in
wrong = abc + xyz;
which will generate an error at runtime because the names we are referring to ( abc and xyz ) have not previously been declared, and hence, do not exist.
In instances where we want to initialize a variable, but without giving it any particular value, we assign it the special value null.
zilch = null;
nothing = 10 * zilch;
Our variable nothing would be equal to zero, as 10 times null, which is the value of zilch, is zero.
If we declare a variable without any value at all, it exists but is undefined.
var zilch;
nothing = 10 * zilch;
In this case, the system assigns the special value NaN to our variable nothing, as zilch is undefined.
The var statement is needed only when declaring variables that are local to a function, meaning variables that are declared only within the function; it is good practice to always declare variables with the var statement, though.
Variables should be named appropriately, so it would be easier to remember what they are for. It is good practice to define variables with names descriptive of the specific roles they play in our script. Aptly named, they can even help to understand what a script does.
JavaScript is a case-sensitive language, so naming a variable aVar is different from naming it AVar. Variable names can be of any length, but must follow certain rules:
- The first character must be a letter, either uppercase or lowercase, an underscore ( _ ), or a dollar sign ( $ ).
- Subsequent characters can be letters, numbers, underscores, or dollar signs.
- The variable name can not be a reserved word.
Examples of valid variable names are:
Examples of invalid variable names are:
- 69 // starts with a number.
- Jack & Jill // the ampersand ( & ) is not a valid character.