Before you use a variable, you should declare (create) it. The process of creating a variable is also known as declaring a variable. When you declare a variable, you tell the computer to reserve some memory for your program to store some data. To declare a variable in JavaScript, use the var command. For instance, the following command creates a variable
var age;
called age. With the above command, computer will reserve some memory and allow you to store to or retrieve from that memory with the name you chose, age. Remember at this point our variable age is null or has a garbage valuewhatever computer's memory slot happens to hold.
You can declare more than one variable by separating each with a comma and still use one var command, as:
var state, city, zip, country;
When you declare a variable, keep the following JavaScript restrictions in mind to a variable name:
Remember that variable names are case-sensitive. In JavaScript, a variable named first_name is considered different from first_Name or FIRST_name.
Also, keep your variable names meaningful. Avoid using a variable name such as k, l, m, z, or a because you may have hard time figuring out what each variable represent in the future or in a long program.
As noted above, to explicitly declare (create) a variable in JavaScript we use the var command. In JavaScript, however, you can also declare variables implicitly by using the assignment operator to assign a value to the new variable. For example,
age = 50;declares a variable called age and signs he integer value 50 to this variable.
The following shows some more examples of variables being created when a value is assigned to a variable:
<script language="javascript">sum = x = y = 0; // declares three variables and each is set to 0.</script>
Alternatively, you may declare and assign the values using the var command:
<script language="javascript">var sum, x, y; // declares multiple variable with the var command.sum = x = y = 0; // sets each variable to 0</script>
So after reviewing the examples above you might be wondering what approach should you take to create variables? Well, as a matter of good programming practice, you should explicitly declare variables with the var command before using. Explicitly declaring a variable helps the browser efficiently and accurately process and manage the variables.