Naming Variables in JavaScript
Using variables is a very important part of programming. It gives you flexibility and control over so many factors and it is really a fundamental part of any program. So, learning how to name variables is important and can save you a lot of time in your programming.
In JavaScript, you can give names to functions, variables, objects, etc. (we will discuss these concepts in future posts). The name you give a variable should be understandable and clear given what you are using it for in your programming. When you are using a variable to hold a person’s age, for example, you may want to call it age instead of something generic like, y.
The name of a variable (or function, etc.) is called an identifier and there are some rules you have to follow:
Identifiers can contain letters, _ underscores, numbers and $ (dollar signs).
Identifiers can not start with a number (you will get an error).
Identifiers are case sensitive (i.e., Age is not the same as age and Name is not the same as name).
Identifiers cannot not be reserved words in JavaScript
There are reserved words in every programming language that have special meaning in a program. Therefore, you can’t use them as a name, or identifier, in your code because they would cause a problem for the computer and the program wouldn’t be able to figure out what you mean because is has special things it does with these reserved words.
For instance,
var age = 99;
Is a way you can declare, name and assign a variable, but if you wrote:
var var = 99;
This would confuse the program and give you an error, because var is a reserved word.
Some reserved words are:
abstract
boolean
break
byte
char
class
const
continue
delete
do
double
else
false
final
float
for
function
if
implements
import
in
int
let
long
new
null
package
private
public
return
short
static
super
switch
this
throw
throws
try
typeof
var
void
while
yield
So, when naming a variable, try to make the name make sense, start it with a letter (for general practice) and try to use camel case lettering to avoid reserved words and to extend the readability of your names.
Camel casing is when the first letter of an identifier is lowercase and the remaining first letters of subsequent words are capitalized. For example:
myAge
taxRate
firstDayOfSchool
Other examples of acceptable identifiers are:
front_line
score
secondGrade