Naming Your Variables

Grade 1, page 5 of 9. A two-minute read.

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)

  1. Names can contain letters, digits, underscores _ and dollar signs $.
  2. Names cannot start with a digit. player1 is fine. 1player is not.
  3. Names cannot contain spaces or hyphens. first name and first-name are both errors.
  4. 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.
  5. Names are case-sensitive: score, Score and SCORE are three different variables.
JavaScriptHas a bug
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. 🐫

JavaScriptFixed
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 nameWhy it's badBetter name
xWhat is x? Nobody knows.playerScore
dataAll values are data!userEmail
nNumber of... what?numberOfGuests
thing2Please, no.secondPlayerName
theTotalPriceOfAllTheItemsInTheCartToo long to typecartTotal

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."

Tip

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.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning