Instruction

Naming Variables

By Guil Hernandez

JavaScript has unique words that you can't use for a variable name, so if you encounter a syntax error when creating a variable, this might be the reason.

reserved words
Reserved keywords – MDN

Other words are reserved for future versions of JavaScript so that they won't cause errors now, but they might in the future. You can view the complete list of current and future reserved keywords in this MDN reference on keywords.

There are a few other rules you'll need to follow as well. Names can't start with a number. So a variable named 9lives is not allowed, but a variable named right1 is. Names can only contain letters, numbers, and the $ and _ characters. So the names numOfUnitsBy# or @home are not allowed, but variables like price$ and created_by are permitted.

Variable names with multiple words

Many programmers use variable names that combine two or more words. It's common to name those variables by either connecting the words with an underscore like price_per_unit or capitalizing every word after the first word like pricePerUnit.

Capitalizing every word following the first is called camel case by programmers because the capital letters look like the humps on the back of a camel!

It's a convention in JavaScript to name variables using the camel case format.

Not Allowed Allowed
9lives right1
pricePer# $price
@home home_alone
price_per_unit
pricePerUnit

What makes a good variable name?

You learned what you can and can't put into a variable name, but what should you put into a variable name? While writing a computer program can be a lot of fun, looking over a program you wrote nine months ago, or a program someone else wrote can often be confusing. Writing clear and understandable code helps make your life easier as a programmer.

Provide clear and descriptive names for your variables

Names like t, n1 or p are short and require less typing, but they don't communicate the purpose of the variables. Even if it requires more typing, use descriptive names like score, playerName, or pricePerPound. Your programs will be a lot easier to understand if you do, and as a programmer, you should always strive to write understandable, readable code.

Confusing Variable Names Descriptive Variable Names
var s = 0; var score = 0;
var n1 = "Jesse"; var playerOne = "Hope";
var p = 10; var pricePerPound = 10;

Resources