The rules
A variable name can contain letters, digits, _ and $. It must follow these rules:
- It cannot start with a digit:
2fastis invalid,fast2is fine. - It cannot contain spaces or hyphens:
my-nameis invalid. - It cannot be a reserved word such as
let,class,returnorfunction. - It is case sensitive:
totalandTotalare different.
const userName = "Maya";
const _private = 1;
const $element = "dollar names are allowed";
const total2 = 5;
console.log(userName, _private, $element, total2);
Use camelCase
The JavaScript convention is camelCase: the first word is lower case and each following word starts with a capital.
const firstName = "Maya";
const totalPrice = 120;
const isLoggedIn = true;
Other conventions exist for other jobs: PascalCase for classes (ShoppingCart) and UPPER_SNAKE_CASE for true constants that are known before the program runs (MAX_ITEMS).
Good names say what a value is
// Hard to read
const d = 7;
const x = d * 24;
// Clear
const daysInWeek = 7;
const hoursInWeek = daysInWeek * 24;
A few habits that help:
- Use whole words:
index, notidx, unless it is a very common short name such asiin a small loop. - Name booleans like questions:
isOpen,hasError,canEdit. - Name arrays with plural words:
users,prices. Name a single item in the singular:user. - Avoid misleading names:
listshould hold a list.
Typos create new names, not errors
let userName = "a"; usrName = "b"; in a non-strict script quietly creates a new global variable. Modules and classes run in strict mode, which turns that into an error, and editors with a linter catch it too.