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.
| Rule | Valid Examples | Invalid Examples |
|---|---|---|
| Must start with a letter, `_`, or `$` | name, _count, $price | 1name, -value, @tag |
| After the first character: letters, digits, `_`, `$` are all fine | user1, total_price, $el | user-name, my value, rate% |
| Cannot be a reserved keyword | myLet, letMe, forEach | let, const, for, if, class |
| No spaces allowed | firstName, first_name | first name |
1// ✅ Valid identifiers2let name = 'Alice';3let userName = 'bob123';4let _private = 'hidden'; // starts with underscore — OK5let $price = 9.99; // starts with $ — OK6let score1 = 100; // digit after first char — OK7let LIMIT = 500; // all uppercase — OK8let camelCase = true;910// ❌ Invalid identifiers — these cause SyntaxError11// let 1name = 'bad'; // starts with a digit12// let my-var = 'bad'; // hyphen not allowed13// let my var = 'bad'; // space not allowed14// let for = 'bad'; // reserved keyword15// let class = 'bad'; // reserved keyword16// let @tag = 'bad'; // @ not allowed1718console.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.
1// ❌ You cannot use keywords as identifier names:2// let let = 5; // SyntaxError3// let const = 5; // SyntaxError4// let for = 5; // SyntaxError5// let if = 5; // SyntaxError6// let class = 5; // SyntaxError7// let return = 5; // SyntaxError89// ✅ But you can use them as PART of a name:10let letValue = 5; // 'let' is part of the name — OK11let forEach = true; // 'for' is part of the name — OK12let myClass = 'math'; // 'class' is part of the name — OK13let returnValue = 42; // 'return' is part of the name — OK1415console.log(letValue, forEach, myClass, returnValue);1617// ✅ 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.
| Convention | Used For | Example |
|---|---|---|
| camelCase | Variables and functions | firstName, getUserData, isLoggedIn |
| PascalCase | Classes and React components | UserProfile, ShoppingCart, TodoItem |
| UPPER_SNAKE_CASE | Constants that never change | MAX_RETRIES, API_URL, TAX_RATE |
| _leadingUnderscore | Private/internal values (by agreement) | _id, _cache, _internal |
| $dollar | jQuery objects or DOM elements | $button, $modal, $form |
1// camelCase — variables and functions2let firstName = 'Alice';3let totalPrice = 49.99;4let isLoggedIn = true;5let itemCount = 0;67function getUserData() {8 return { name: firstName };9}10function calculateTotal(price, tax) {11 return price + price * tax;12}1314// PascalCase — classes15class UserProfile {16 constructor(name) {17 this.name = name;18 }19 greet() {20 return `Hello, ${this.name}!`;21 }22}2324// UPPER_SNAKE_CASE — constants that never change25const MAX_ITEMS = 100;26const TAX_RATE = 0.18;27const API_URL = 'https://api.example.com';28const DEFAULT_LANG = 'en';2930// _leadingUnderscore — private / internal (convention only)31class Counter {32 constructor() {33 this._count = 0; // signals: don't touch this directly34 }35 increment() {36 this._count++;37 }38 get value() {39 return this._count;40 }41}4243// Run it44const user = new UserProfile('Bob');45console.log(user.greet()); // Hello, Bob!46console.log(calculateTotal(100, TAX_RATE)); // 1184748const 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.
1// ❌ Bad names — impossible to understand2let x = 25;3let d = new Date();4let a = [];5let temp = fetchUser();6function calc(v, r) {7 return v * r;8}910// ✅ Good names — reads like English11let userAge = 25;12let currentDate = new Date();13let cartItems = [];14let currentUser = fetchUser();15function calculateTax(price, taxRate) {16 return price * taxRate;17}1819// ✅ Boolean names — use is/has/can/should prefix20let isActive = true;21let hasPermission = false;22let canEdit = true;23let shouldRedirect = false;2425// ✅ Function names — start with a verb26function getUser() {} // get something27function setTheme() {} // set something28function createPost() {} // create something29function deleteItem() {} // delete something30function validateForm() {} // validate something31function isAdmin() {} // check something (returns boolean)3233console.log('userAge:', userAge);34console.log('isActive:', isActive);35console.log('Tax on 100:', calculateTax(100, 0.18));3637function fetchUser() { return { name: 'Alice' }; }38console.log('currentUser:', currentUser);
- 1Be descriptive, not short.
userAgeis better thana.cartItemCountis better thann. - 2Boolean variables should start with
is,has,can, orshould: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).usrNmis harder to read thanuserName. - 6Avoid single letters except in short loops (
i,j) or math (x,y,r).
Test Your Knowledge
Test Your Knowledge
Which of these is a valid JavaScript identifier?
Which naming convention is used for class names in JavaScript?
Why can't you use let as a variable name?
Which of these is the best name for a boolean variable that checks if a user is logged in?
Which of these is the correct way to name a constant for the maximum number of login attempts?
Quick Reference
Identifiers — Quick Reference
- 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,classas names. - 5JavaScript is case-sensitive —
score,Score, andSCOREare 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, orshould:isActive,hasError. - 10Start function names with a verb:
getUser,createPost,deleteItem.
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.