To use a variable, you first have to declare it. Declaring a variable is roughly a statement of intention to use a variable in the program. A variable declaration reserves memory for the variable, and informs the browser that all references to the variable name aren't mistakes. If you forget to declare a variable, the browser will become confused and generate an error message. To declare a variable, simply type the 'var' keyword, followed by the name you wish to assign to the variable. Like the rest of JavaScript, variable names are case sensitive. Valid names can begin with either a letter or an underscore, followed by letters, underscores, and numbers. To create a variable 'myVariable', you would type:
var myVariable;
Now that you have variables, you need to put something in them. Singular actions in JavaScript are accomplished using statements. A statement is an instruction to the computer to perform a task. In this case, we want to assign a value to a variable. To do this, we will use the assignment operator (=), which assigns the value on the right-hand side to the variable name on the left-hand side. To place the value '5' in 'myVariable', you would type:
myVariable = 5;
It is important not to confuse this expression with its mathematical meaning. The above statement places five in the variable 'myVariable', and makes no assumptions about the equality of the two values. For example, to increment 'myVariable' by one, we could write:
myVariable = myVariable + 1;
In this example, the value on the right-hand side of the equals sign (myVariable + 1) is assigned to the left-hand side of the equation (myVariable). Mathematically, the statement makes no sense, but it is one of the most common programming instructions. If we had instead wanted to store a string myVariable, we could have typed:
myVariable = "This is a string.";
Notice that strings are enclosed in either double or single quotation marks. The sentence above could have been written:
myVariable = 'This is a string.';
The only stipulation is that you cannot open a string with a single quote and then close it with a double quote, or vice versa.