1. Computing

JavaScript Variables and Operators

4. Naming Variables


The instructions that we give in JavaScript will contain actions to be performed as well as variables. In order for JavaScript to be understand which parts of you code are variables, the names you use for variables must obey the following rules

  • JavaScript variable names start with a letter, $, or underscore.
  • Names can only contain contains letters, numbers, $ and underscores so no spaces or other special characters.
  • You can't use a specific set of words called reserved words (which have special meanings) as variable names.
  • JScript (Internet Explorer's equivalent to JavaScript) automatically maps HTML fields with names and ids to the equivalent variable in JScript so you need to avoid using the same name in both places. This is one of the most common reasons for scripts, that run quite nicely in most web browsers, to malfunction when you test them in Internet Explorer.

Variable names in JavaScript are case sensitive which means that variables that are the same except for some letters being capitalized in one and not the other are considered to be different variable names. Here are some examples of valid variable names.

1 i
2 an_apple
3 numberOfMonkeysThatFitInABarrel
4 $floater
5 harry03

1 is the single letter i. Using short variable names such as this can result in your ending up with much shorter code and involves a lot less typing. The down side is that short names like this are not very descriptive of what the variable contains. The use of names this short is therefore best avoided under most circumstances.

2 an_apple is an example of one of the ways that you can incorporate multiple words into a variable name so as to make it more descriptive and to avoid conflicts with the reserved words. The practice of separating the words in variable names with underscores is not so popular now as it used to be.

The preferred way these days for using multiple words in a variable name is what is known as camelCase where the first letter of each word is a capital and the rest of the word is in lowercase. 3 numberOfMonkeysThatFitInABarrel demonstrates both the use of camelCase and also shows that if we want to we can use really long variable names. This one is actually longer than it really needs to be since the 'numberOf' on the front doesn't really add anything useful in terms of working out what the variable is likely to contain and so calling that field monkeysThatFitInABarrel would be a better name to use.

4 and 5 show how we can also validly use $ and numbers in our variable names as well as letters and underscores.

This tutorial first appeared on www.felgall.com and is reproduced here with the permission of the author.

©2014 About.com. All rights reserved.