javascript

Identifiers and Naming Conventions

Learn what identifiers are in JavaScript, the rules for naming variables and functions, and the naming conventions every developer follows.

8 min read 7 sections Tutorial
Share

Identifiers & Naming Rules

Identifiers & Naming Rules

An identifier is the name you give to something in JavaScript — a variable, a function, a class, or a label. Every time you write let age = 25 or function greet(), the words age and greet are identifiers.

JavaScript has strict rules about what names are allowed. If you break these rules, you get a SyntaxError and your code won't run.

Identifiers are everywhere

Every name you create in JavaScript is an identifier:

  • Variable names: let **score** = 100;
  • Function names: function **greet**() {}
  • Class names: class **User** {}
  • Parameter names: function add(**a**, **b**) {}
  • Object property names are NOT identifiers — they follow different rules.
📏

Rules

Hard rules you must follow. Breaking them causes a SyntaxError.

📐

Conventions

Soft rules agreed on by developers. Breaking them won't crash your code — but it confuses everyone.

🔤

Case Sensitive

score, Score, and SCORE are three completely different identifiers.

🚫

Reserved Words

Words like let, if, return belong to JavaScript. You cannot use them as names.

Naming Rules

The Rules for Naming Identifiers

These are hard rules. JavaScript will throw a SyntaxError if you break any of them. There are only 4 rules to remember.

RuleValid ExamplesInvalid Examples
Must start with a letter, `_`, or `$`name, _count, $price1name, -value, @tag
After the first character: letters, digits, `_`, `$` are all fineuser1, total_price, $eluser-name, my value, rate%
Cannot be a reserved keywordmyLet, letMe, forEachlet, const, for, if, class
No spaces allowedfirstName, first_namefirst name
javascript
1// ✅ Valid identifiers
2let name = 'Alice';
3let userName = 'bob123';
4let _private = 'hidden'; // starts with underscore — OK
5let $price = 9.99; // starts with $ — OK
6let score1 = 100; // digit after first char — OK
7let LIMIT = 500; // all uppercase — OK
8let camelCase = true;
9
10// ❌ Invalid identifiers — these cause SyntaxError
11// let 1name = 'bad'; // starts with a digit
12// let my-var = 'bad'; // hyphen not allowed
13// let my var = 'bad'; // space not allowed
14// let for = 'bad'; // reserved keyword
15// let class = 'bad'; // reserved keyword
16// let @tag = 'bad'; // @ not allowed
17
18console.log(name, userName, _private, $price, score1);

Hyphens are NOT allowed in identifiers

You cannot use a hyphen - in a JavaScript identifier. my-name is NOT a valid variable name — it looks like subtraction to JavaScript (my minus name).

CSS uses hyphens (background-color), but JavaScript uses camelCase (backgroundColor). This trips up many beginners who are used to CSS.

Reserved Keywords

Reserved Keywords

Reserved keywords are words that JavaScript already uses for its own grammar. You cannot use them as variable or function names. If you try, you get a SyntaxError.

javascript
1// ❌ You cannot use keywords as identifier names:
2// let let = 5; // SyntaxError
3// let const = 5; // SyntaxError
4// let for = 5; // SyntaxError
5// let if = 5; // SyntaxError
6// let class = 5; // SyntaxError
7// let return = 5; // SyntaxError
8
9// ✅ But you can use them as PART of a name:
10let letValue = 5; // 'let' is part of the name — OK
11let forEach = true; // 'for' is part of the name — OK
12let myClass = 'math'; // 'class' is part of the name — OK
13let returnValue = 42; // 'return' is part of the name — OK
14
15console.log(letValue, forEach, myClass, returnValue);
16
17// ✅ These words are NOT reserved (but avoid them — confusing):
18let undefined2 = 'not a keyword technically';
19let NaN2 = 99;
20console.log(undefined2, NaN2);

Naming Conventions

Naming Conventions

Conventions are not enforced by JavaScript — your code will still run if you ignore them. But every professional JavaScript developer follows these conventions. When you work on a team or read someone else's code, these conventions tell you immediately what each name is.

Think of it like wearing a uniform. It is not a law, but it makes everything clearer.

ConventionUsed ForExample
camelCaseVariables and functionsfirstName, getUserData, isLoggedIn
PascalCaseClasses and React componentsUserProfile, ShoppingCart, TodoItem
UPPER_SNAKE_CASEConstants that never changeMAX_RETRIES, API_URL, TAX_RATE
_leadingUnderscorePrivate/internal values (by agreement)_id, _cache, _internal
$dollarjQuery objects or DOM elements$button, $modal, $form
javascript
1// camelCase — variables and functions
2let firstName = 'Alice';
3let totalPrice = 49.99;
4let isLoggedIn = true;
5let itemCount = 0;
6
7function getUserData() {
8 return { name: firstName };
9}
10function calculateTotal(price, tax) {
11 return price + price * tax;
12}
13
14// PascalCase — classes
15class UserProfile {
16 constructor(name) {
17 this.name = name;
18 }
19 greet() {
20 return `Hello, ${this.name}!`;
21 }
22}
23
24// UPPER_SNAKE_CASE — constants that never change
25const MAX_ITEMS = 100;
26const TAX_RATE = 0.18;
27const API_URL = 'https://api.example.com';
28const DEFAULT_LANG = 'en';
29
30// _leadingUnderscore — private / internal (convention only)
31class Counter {
32 constructor() {
33 this._count = 0; // signals: don't touch this directly
34 }
35 increment() {
36 this._count++;
37 }
38 get value() {
39 return this._count;
40 }
41}
42
43// Run it
44const user = new UserProfile('Bob');
45console.log(user.greet()); // Hello, Bob!
46console.log(calculateTotal(100, TAX_RATE)); // 118
47
48const counter = new Counter();
49counter.increment();
50counter.increment();
51console.log('Count:', counter.value); // 2

Writing Good Names

How to Write Good Names

The biggest mistake beginners make is using short, meaningless names like x, a, temp, or data. These make code very hard to understand later.

Good names make your code read like plain English. A good name tells you exactly what the value is — without needing a comment.

javascript
1// ❌ Bad names — impossible to understand
2let x = 25;
3let d = new Date();
4let a = [];
5let temp = fetchUser();
6function calc(v, r) {
7 return v * r;
8}
9
10// ✅ Good names — reads like English
11let userAge = 25;
12let currentDate = new Date();
13let cartItems = [];
14let currentUser = fetchUser();
15function calculateTax(price, taxRate) {
16 return price * taxRate;
17}
18
19// ✅ Boolean names — use is/has/can/should prefix
20let isActive = true;
21let hasPermission = false;
22let canEdit = true;
23let shouldRedirect = false;
24
25// ✅ Function names — start with a verb
26function getUser() {} // get something
27function setTheme() {} // set something
28function createPost() {} // create something
29function deleteItem() {} // delete something
30function validateForm() {} // validate something
31function isAdmin() {} // check something (returns boolean)
32
33console.log('userAge:', userAge);
34console.log('isActive:', isActive);
35console.log('Tax on 100:', calculateTax(100, 0.18));
36
37function fetchUser() { return { name: 'Alice' }; }
38console.log('currentUser:', currentUser);
Pro Tips
  • 1Be descriptive, not short. userAge is better than a. cartItemCount is better than n.
  • 2Boolean variables should start with is, has, can, or should: isLoggedIn, hasError, canSubmit.
  • 3Functions should start with a verb: getUser, setTheme, createPost, deleteItem, validateForm.
  • 4Constants that never change should be UPPER_SNAKE_CASE: MAX_SIZE, API_KEY.
  • 5Avoid abbreviations unless they are universally known (url, id, api). usrNm is harder to read than userName.
  • 6Avoid single letters except in short loops (i, j) or math (x, y, r).

Test Your Knowledge

Test Your Knowledge

Quick Check

Which of these is a valid JavaScript identifier?

Quick Check

Which naming convention is used for class names in JavaScript?

Quick Check

Why can't you use let as a variable name?

Quick Check

Which of these is the best name for a boolean variable that checks if a user is logged in?

Quick Check

Which of these is the correct way to name a constant for the maximum number of login attempts?

Quick Reference

Identifiers — Quick Reference

Pro Tips
  • 1An identifier is any name you create — for variables, functions, classes, or parameters.
  • 2Names must start with a letter, _, or $. After that, digits are also allowed.
  • 3No hyphens, spaces, or special characters (except _ and $).
  • 4You cannot use reserved keywords like let, const, if, for, class as names.
  • 5JavaScript is case-sensitivescore, Score, and SCORE are three different names.
  • 6Use camelCase for variables and functions: firstName, getUserData.
  • 7Use PascalCase for classes: UserProfile, ShoppingCart.
  • 8Use UPPER_SNAKE_CASE for constants: MAX_SIZE, TAX_RATE.
  • 9Start booleans with is, has, can, or should: isActive, hasError.
  • 10Start function names with a verb: getUser, createPost, deleteItem.
Continue Learning
📦

Variables

let, const, and var — how to store values and what makes each one different.

🔀

Statements & Semicolons

How JavaScript statements work and when semicolons are needed.

🔡

Case Sensitivity

How uppercase and lowercase affect your code in JavaScript.

🔧

Functions

How to write and name functions — the building blocks of every program.

You know JavaScript identifiers!

You can now name variables, functions, and classes correctly. You know the 4 hard rules, the naming conventions, and how to write names that make your code easy to read. Good naming is one of the most valuable skills in programming.

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning