JavaScript Variable Names
A variable is a named storage location in the computer's RAM memory where you can store data and later retrieve it. A box with a label on it makes a good analogy. When you store something in a box in the closet, you might put a descriptive label on the box to indicate its contents. The name of a variable is kind of like a label, but the box is inside the computer's memory. Of course, when you have lots of boxes (or variables), accurate and descriptive labels help to keep track of what's inside all of them.
The programmer gets to choose the names of variables, but there are rules.
Rules for variable names that are fatal if violated:
-
Variable names can only contain letters, digits, underscores. (Dollar signs ($) are also allowed, but are used for purposes well beyond the scope of this course.)
-
Variable names must begin with a letters. (Can begin with $ or _ but again well beyond the scope of this course.)
-
Variable names must NOT be JavaScript reserved keywords like
var
, document
, write
, prompt
, and other built-in keywords you will see.
Non-fatal rules for naming variables:
-
Variable names should be descriptive of the data that will be stored in the variable. The previous example scripts could have used variable names such as
x
and y
, but using side
and area
made the code easier for a human to understand. For small programs, this is a convenience for programmers, for larger programs with lots of variables to keep track of, this becomes imperative.
-
Variable names are case sensitive. If you use a variable such as
side
to store some data, but then later use Side
when retrieving the data, you won't get the data. This is not a fatal error, but if you use the unknown Side
variable in the output, you will see a value like undefined
.