AI Hints
Home›JavaScript Tutorial›Names, Numbers and Strings
JavaScript · Lesson 7 of 138

Naming Variables

CamelCase and rules.

⏱ 2 min read▶ Video at 6:32🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Good names make code easy to read. Bad names make it a puzzle. JavaScript has a few strict rules about names, and a few habits that every developer follows.

Naming Variables
From the video: Naming Variables
  • Good names are readable
  • Bad names are puzzles
  • Rules and habits

The rules

Names can contain letters, digits, underscores, and dollar signs, but they can't start with a digit. They can't contain spaces or dashes. They can't be special words, like let or const. And they're case sensitive, so score with a small S and Score with a capital S are different variables.

NameAllowed?
userNameyes
total2yes
2totalno, starts with a digit
user-nameno, a dash
letno, a keyword

camelCase

The JavaScript habit is camel case. Start with a small letter, and give each new word a capital letter, like humps on a camel. Choose names that say what's inside. Run it.

app.jsjavascript
const firstName = "Ana";
const itemsInCart = 3;
const isLoggedIn = true;

console.log(firstName, itemsInCart, isLoggedIn);
Output
Ana 3 true

Good names and bad names

Compare these two pieces of code. They do exactly the same thing. The first uses names like x, y, and z, so you have to guess what they mean. The second uses clear names, so the code explains itself. Good names are the cheapest way to make code easier to read. Run it.

app.jsjavascript
const x = 12;
const y = 2.5;
const z = x * y;
console.log(z);

const ticketsSold = 12;
const ticketPrice = 2.5;
const totalSales = ticketsSold * ticketPrice;
console.log(totalSales);
Output
30
30

Summary

Names can't start with a digit, or contain spaces, and they're case sensitive. Use camel case, and descriptive names. Next, numbers.

Key takeaways
  • camelCase
  • Descriptive names
  • Case sensitive
Next up: Numbers — maths in JavaScript