Naming things is one of the trickiest parts of programming. There's an old programmer joke:
"There are only two hard things in computer science: cache invalidation and naming things."
You don't need to know what "cache invalidation" is. But you do need to know how to name things, so let's go.
The rules (JavaScript enforces these)
- Names can contain letters, digits, underscores
_and dollar signs$. - Names cannot start with a digit.
player1is fine.1playeris not. - Names cannot contain spaces or hyphens.
first nameandfirst-nameare both errors. - Names cannot be reserved words: words that JavaScript already uses for itself, like
let,const,if,for,function,return,class,true,false, and a few dozen others. - Names are case-sensitive:
score,ScoreandSCOREare three different variables.
let 2fast = "car"; // starts with a digit
let first name = "Zoe"; // contains a space
let my-age = 30; // contains a hyphen
let const = 5; // "const" is a reserved word
The conventions (humans expect these)
These aren't enforced by JavaScript, but every JavaScript developer follows them, and your code will look weird if you don't.
Use camelCase. When a name is made of several words, write the first word in lowercase and start each following word with a capital letter, with no spaces. It's called camelCase because the capital letters stick up like the humps on a camel. 🐫
let firstName = "Zoe";
let totalPrice = 49.99;
let numberOfStudents = 32;
let isLoggedIn = true;
Make names meaningful. Your variable names should describe what's inside the box.
| Bad name | Why it's bad | Better name |
|---|---|---|
x | What is x? Nobody knows. | playerScore |
data | All values are data! | userEmail |
n | Number of... what? | numberOfGuests |
thing2 | Please, no. | secondPlayerName |
theTotalPriceOfAllTheItemsInTheCart | Too long to type | cartTotal |
Booleans often start with is, has or can. (A boolean is a true/false value; you'll meet them in Grade 2.) Names like isOpen, hasPaid and canVote read like yes/no questions, which is exactly what they are.
Truly fixed values are sometimes written in UPPER_SNAKE_CASE. For constants that are hard-coded settings, like const MAX_PLAYERS = 4; or const TAX_RATE = 0.15;, many developers use all capitals with underscores between words. This shouts "THIS IS A FIXED SETTING, DON'T EVEN THINK ABOUT IT."
A good test for a variable name: if you showed just the name to a friend, could they guess what's inside? daysUntilBirthday? Easy. d? No chance.