A variable is a name in memory that points to a value. Variables help us keep track of values in memory so that we can always access them within our programs. We can give variables names so that it is easier to access them in our programs. We can also access and change the values of variables whenever we choose to.
Examples of Variables
The following code shows how to create three different variables. It is good practice to use camel case to name your variables.
var highScore; var gameOverString; var isGameOver;
We can also assign values when we create variables.
var highScore = 1000; var gameOverString = "Game Over!"; var isGameOver = false;
Another way to assign values would be to create the variable first, then assign the value later.
var highScore; var gameOverString; var isGameOver; highScore = 1000; gameOverString = "Game Over!"; isGameOver = false;
Variables are only allowed to have letters, numbers, underscores, or dollar signs. But, one thing to note is that variables can't start with a number!
var name; //Good! var _name; //Still good! var $name; //This works good too! var 1name; //No! No! No! Error!
If the variable name has other characters that are not letters, numbers, underscores or dollar signs, then the variable is invalid.
var na1me; //Good! var na$me; //Still good! var na_me; //You best believe it's good! var na%me; //No! Error! % is not allowed in variable names! var ~name; //No again! Error! ~ is not allowed in variable names!
break case catch continue debugger default delete do else finally for function if in instanceof new return switch this throw try typeof var void while with
However, just because the words are reserved doesn't mean we can't fully use them. It just means we have be more descriptive with the name. The following shows examples of how we can still use the reserved names in our own variable names.
var new; // This is an error. We can't create a variable with a reserved name. var newImage; // Although we used the reserved word "new", this is fine since it's not the exact word. var return; // Error, "return" is a reserved word. var returnValue; // This works fine!