JavaScript Variable Naming Conventions & Rules
Master JavaScript variable naming conventions including camelCase, UPPER_SNAKE_CASE, and PascalCase. Learn the syntax rules, naming best practices, and common anti-patterns that every developer should know.
Choosing good variable names is one of the most underrated skills in programming. Clear, consistent naming turns your code into a narrative that other developers (and your future self) can follow without extra comments or documentation. Poor naming does the opposite: it forces readers to trace through logic to figure out what d, temp2, or data actually represents.
JavaScript has two layers of naming rules. The first layer is syntax rules: hard requirements enforced by the language itself. Break these, and your code throws a SyntaxError. The second layer is conventions: community-agreed patterns that make code consistent and readable. Break these, and your code still runs, but other developers will struggle to read and maintain it.
This guide covers both layers, with practical examples and the reasoning behind each convention.
Syntax Rules: What JavaScript Allows
Before discussing style, you need to know what the JavaScript language permits as valid identifiers (variable names, function names, class names).
Valid Characters
// ALLOWED: letters, digits, underscore, dollar sign
let firstName = "Alice"; // Letters only
let user2 = "Bob"; // Letters and digits
let _privateValue = 42; // Starts with underscore
let $element = document.body; // Starts with dollar sign
let café = "latte"; // Unicode letters (accented characters)
let π = 3.14159; // Unicode symbols (technically valid)
// NOT ALLOWED: starting with a digit
// let 2ndPlace = "Silver"; // SyntaxError: Invalid or unexpected token
// NOT ALLOWED: hyphens, spaces, or most special characters
// let first-name = "Alice"; // SyntaxError (hyphen treated as minus)
// let first name = "Alice"; // SyntaxError (space breaks identifier)
// let my@var = 5; // SyntaxError (@ is not allowed)| Rule | Valid Example | Invalid Example | Why |
|---|---|---|---|
Must start with letter, _, or $ | count, _id, $ref | 2count, @name | Digits and special characters cannot begin identifiers |
| Rest can include digits | user1, item_2 | item-2 | Hyphens are the minus operator |
| No spaces | firstName | first name | Spaces terminate the identifier |
| Case-sensitive | Name ≠ name | n/a | JavaScript distinguishes uppercase and lowercase |
| No reserved words | score | class, return | Reserved words have built-in language meaning |
Reserved Words You Cannot Use
JavaScript reserves certain words for its own syntax. Using them as variable names produces a SyntaxError:
// These are all SyntaxErrors:
// let class = "Math";
// let return = true;
// let function = "add";
// let if = false;
// let const = 5;
// Common reserved words to avoid:
// break, case, catch, class, const, continue, debugger, default,
// delete, do, else, export, extends, finally, for, function, if,
// import, in, instanceof, let, new, return, static, super, switch,
// this, throw, try, typeof, var, void, while, with, yield[Strict Mode](/tutorials/programming-languages/javascript/javascript-strict-mode-use-strict-explained) Adds More Restrictions
In strict mode ("use strict";) and ES modules, additional words are reserved: implements, interface, package, private, protected, public. These exist because they might become keywords in future JavaScript versions.
Naming Conventions: Community Standards
These conventions are not enforced by the language, but they are followed by virtually every professional JavaScript codebase.
camelCase for Variables and Functions
Regular variables and function names use camelCase: the first word is lowercase, and each subsequent word starts with an uppercase letter.
// Variables: camelCase
let currentUser = null;
let isAuthenticated = false;
let shoppingCartTotal = 0;
let maxRetryCount = 3;
// Functions: camelCase
function calculateShippingCost(weight, distance) {
return weight * 0.5 + distance * 0.1;
}
function formatCurrency(amount) {
return `$${amount.toFixed(2)}`;
}
// Event handlers: camelCase with "handle" or "on" prefix
function handleSubmitClick(event) {
event.preventDefault();
}
function onUserLogin(credentials) {
// process login
}UPPER_SNAKE_CASE for Constants
Values that are known at write-time and never change throughout the program's lifetime use UPPER_SNAKE_CASE: all uppercase letters with underscores separating words.
// True constants: values that never change
const MAX_FILE_SIZE_BYTES = 5242880; // 5 MB
const API_BASE_URL = "https://api.example.com/v2";
const HTTP_STATUS_OK = 200;
const DEFAULT_TIMEOUT_MS = 30000;
const TAX_RATE = 0.08;
// NOT constants (even though declared with const):
// These are computed at runtime or change between runs
const currentDate = new Date(); // Use camelCase: runtime value
const userSettings = getUserSettings(); // Use camelCase: runtime value
const randomId = Math.random(); // Use camelCase: different each timeThe distinction matters: const in JavaScript means the binding cannot be reassigned, but the value might be dynamic. UPPER_SNAKE_CASE is reserved for values that are truly fixed and known before the code runs.
PascalCase for Classes and Constructors
Class names and constructor functions use PascalCase: every word starts with uppercase, including the first.
// Classes: PascalCase
class ShoppingCart {
constructor() {
this.items = [];
}
addItem(product) {
this.items.push(product);
}
getTotal() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
}
// Constructor functions (older pattern): PascalCase
function DatabaseConnection(host, port) {
this.host = host;
this.port = port;
}
// React components: PascalCase
function UserProfile({ name, email }) {
return `<div>${name} (${email})</div>`;
}Summary Table
| Convention | Use For | Examples |
|---|---|---|
camelCase | Variables, functions, methods, parameters | userName, calculateTotal(), isValid |
UPPER_SNAKE_CASE | True constants (known at write-time) | MAX_RETRIES, API_KEY, PI |
PascalCase | Classes, constructors, React components | UserService, HttpClient, NavBar |
_prefixCamelCase | Private/internal variables (convention) | _internalCache, _socket |
$prefixCamelCase | DOM elements, jQuery/framework refs | $modal, $submitButton |
Naming Best Practices: Writing Self-Documenting Code
Be Descriptive and Specific
// BAD: vague, single-letter, or abbreviated names
let d = new Date();
let arr = [1, 2, 3];
let temp = getUserData();
let n = items.length;
// GOOD: descriptive names that explain what the variable holds
let registrationDate = new Date();
let studentScores = [1, 2, 3];
let currentUserProfile = getUserData();
let totalItemCount = items.length;Use Boolean Prefixes
Boolean variables should read like a yes/no question. Prefix them with is, has, can, should, or was.
// Clear boolean naming
let isVisible = true;
let hasPermission = false;
let canEdit = user.role === "admin";
let shouldAutoSave = preferences.autoSave;
let wasSuccessful = response.status === 200;
// BAD: ambiguous boolean names
let visible = true; // Is this a boolean or a CSS value?
let permission = false; // Is this a string, object, or boolean?
let edit = true; // Is this a function or a flag?Use Verb Prefixes for Functions
Functions perform actions, so their names should start with a verb.
// Functions do things: use verbs
function fetchUserProfile(userId) { /* ... */ }
function calculateDiscount(total, code) { /* ... */ }
function validateEmailAddress(email) { /* ... */ }
function formatPhoneNumber(raw) { /* ... */ }
function parseCSVRow(line) { /* ... */ }
// getters return a value
function getFullName(user) {
return `${user.firstName} ${user.lastName}`;
}
// checkers return a boolean
function isExpired(token) {
return Date.now() > token.expiresAt;
}Plurals for Collections
// Singular for individual items
const user = { name: "Alice", age: 28 };
const product = { id: 1, title: "Keyboard" };
// Plural for collections (arrays, sets, maps)
const users = [user1, user2, user3];
const products = productCatalog.getAll();
const selectedIds = new Set([1, 5, 12]);
// Loop variables use singular of the collection name
for (const user of users) {
console.log(user.name);
}
products.forEach(product => {
console.log(product.title);
});Anti-Patterns: Names to Avoid
These Naming Patterns Cause Real Problems
Recognizing bad naming patterns helps you avoid them in your own code and spot them in code reviews.
// ANTI-PATTERN 1: Single-letter names (except loop counters)
let x = getUser(); // What is x?
let d = new Date(); // d could be anything
// Acceptable: for (let i = 0; i < 10; i++) { ... }
// ANTI-PATTERN 2: Generic names that say nothing
let data = fetchFromAPI(); // What kind of data?
let info = processResults(); // What info specifically?
let stuff = getPageContent(); // Completely meaningless
// Better: let userProfile = fetchFromAPI();
// ANTI-PATTERN 3: Names that lie about the type
let isReady = "almost"; // Name implies boolean, value is string
let userCount = "seventeen"; // Name implies number, value is string
let userList = { a: 1, b: 2 }; // Name implies array, value is object
// ANTI-PATTERN 4: Inconsistent naming in the same file
let user_name = "Alice"; // snake_case
let userAge = 28; // camelCase
let UserRole = "admin"; // PascalCase for a regular variable
// Pick one convention (camelCase) and stick with it
// ANTI-PATTERN 5: Meaningless number suffixes
let temp1 = getWidth();
let temp2 = getHeight();
let temp3 = getDepth();
// Better: let width, height, depthBest Practices
Follow a consistent naming convention across your entire project. Mixing camelCase, snake_case, and PascalCase for the same type of identifier (regular variables) creates cognitive overhead. Configure ESLint to enforce naming conventions automatically.
Name variables for what they represent, not how they are computed. filteredResults is better than arrayAfterFilter. averageRating is better than sumDividedByCount. Focus on the "what," not the "how."
Keep names as short as possible while remaining clear. userPermissions is fine; arrayOfAllUserPermissionsForCurrentSession is too verbose. Aim for enough words to be unambiguous, then stop.
Use the same vocabulary consistently. If you call it user in one file, do not call it customer, person, and account in other files when referring to the same concept. Pick one term and use it everywhere.
Let your IDE help you. Modern editors like VS Code suggest variable names based on context. Use these suggestions and rename refactoring tools to keep names consistent across your codebase.
Common Mistakes and How to Avoid Them
Naming Mistakes That Hurt Code Quality
These patterns make code harder to read, debug, and maintain.
Using abbreviations that only you understand. usrPrfMgr might make sense when you write it, but three months later (or to a new team member) it is unreadable. Write userProfileManager instead; modern editors auto-complete long names.
Reusing variable names for different purposes. Reassigning result three times in a function to hold three different types of data is confusing. Give each value its own descriptive name.
Naming boolean variables without a prefix. loading, open, and active are ambiguous. isLoading, isOpen, and isActive clearly communicate that these hold true/false values.
Using camelCase for class names. Classes represent blueprints for objects and by convention use PascalCase. Naming a class userService instead of UserService makes it look like a regular variable, hiding the fact that it should be instantiated with new.
Next Steps
Understand global vs local variables
Learn how global and local scope affects where your variables are accessible and why minimizing global variables is a core best practice.
Compare var, let, and const in depth
Dive into the var vs let vs const comparison to understand hoisting behavior, the temporal dead zone, and scope differences.
Configure ESLint for naming rules
Set up ESLint with the camelcase and naming-convention rules to automatically enforce consistent naming across your entire project.
Review real-world codebases
Browse popular open-source JavaScript projects on GitHub to see how experienced developers name variables, functions, and modules in production code.
Rune AI
Key Insights
- camelCase for variables and functions: This is the universal JavaScript convention for identifiers:
userName,calculateTotal() - UPPER_SNAKE_CASE for true constants: Reserve this for values known at write-time that never change:
MAX_FILE_SIZE,API_URL - PascalCase for classes: Class names start every word with uppercase to distinguish them from regular variables:
UserService,HttpClient - Boolean prefixes: Use
is,has,can,shouldto make boolean intent clear:isLoading,hasPermission - Consistency over cleverness: Pick conventions, document them, and enforce them with a linter; inconsistent naming causes more confusion than any single bad name
Frequently Asked Questions
Is camelCase the only accepted convention in JavaScript?
Can I use Unicode characters in variable names?
Why do some variables start with an underscore?
Should I name loop variables i, j, k or use descriptive names?
How long should variable names be?
Conclusion
Variable naming is where code quality begins. Following JavaScript's syntax rules keeps your code from crashing, while following community conventions (camelCase for variables, UPPER_SNAKE_CASE for constants, PascalCase for classes) makes it readable and maintainable. The best variable names are descriptive enough to eliminate the need for comments, consistent enough to establish patterns, and short enough to keep code scannable.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.