Skip to content
jshacks.dev
Fundamentals

Naming Conventions in JavaScript With Practical Examples

The JavaScript naming conventions that matter: camelCase, PascalCase, constants, booleans, files, acronyms and units. With a case converter and linter rules.

9 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Node.js and Vite logos.

JavaScript has no naming rules beyond what the parser requires, and a codebase that follows no convention reads like several codebases stitched together. The language's own library gives the pattern most teams adopt: camelCase for variables, functions and methods, PascalCase for classes and constructors, and capitals for true constants. Around that core sit a handful of choices that decide whether a name tells the reader what they need: how to name booleans, how to write acronyms, how to name files, whether to mark a private member, and how to put units into a name. This post sets out the conventions we follow, with the reasoning for each, a pair of examples where it helps, a case conversion helper with its output, the problem of names that collide with globals, and the linter settings that enforce all of it without a review comment. The examples run on Node.js 24.

The core: three cases

Kind of nameCaseExample
Variables, parameters, functions, methods, propertiescamelCaseuserCount, parseDate()
Classes, constructors, React components, TypeScript typesPascalCaseUserAccount, HttpClient
Module-level constants that never changeUPPER_SNAKE_CASEMAX_RETRIES, DEFAULT_TIMEOUT_MS
Files and folderskebab-case, or match the exportuser-account.js, UserAccount.js
Environment variablesUPPER_SNAKE_CASEDATABASE_URL
JavaScript
const MAX_RETRIES = 3;

class RetryPolicy {
  #attempts = 0;

  shouldRetry(error) {
    this.#attempts += 1;
    return this.#attempts <= MAX_RETRIES && error.retryable === true;
  }
}

const policy = new RetryPolicy();
const results = [1, 2, 3, 4].map(() => policy.shouldRetry({ retryable: true }));

console.log(results);
Text
[ true, true, true, false ]

The constant is capitalized because it is a fixed value known when the module loads. A value that is computed, such as the result of a function call, or an object that you mutate, is a camelCase variable even if it is declared with const, because const means the binding is fixed and not that the value is a constant in the sense the capitals promise. The class is PascalCase, which signals that it should be called with new. A reader can tell what each name is before reading its definition.

Name functions with verbs and values with nouns

A function does something, so its name starts with a verb. A variable holds something, so its name is a noun.

JavaScript
const users = [
  { id: 1, name: "Ada", active: true },
  { id: 2, name: "Grace", active: false },
  { id: 3, name: "Linus", active: true },
];

const activeUsers = users.filter((user) => user.active);
const userNames = activeUsers.map((user) => user.name);
const usersById = new Map(users.map((user) => [user.id, user]));

function findUserById(id) {
  return usersById.get(id) ?? null;
}

console.log(userNames, findUserById(2)?.name, findUserById(9));
Text
[ 'Ada', 'Linus' ] Grace null

Collections are plural, and a lookup structure says how it is keyed: usersById tells you that usersById.get(2) takes an id. The singular form belongs to the element, as in user inside the callback. The function name findUserById says what it does and what it takes, which means a call such as findUserById(2) needs no comment. Avoid vague verbs such as handle, process and do unless the context is narrow, since processData tells nobody anything.

Booleans read as questions

A boolean name should make the if statement read as a sentence.

JavaScript
const isEmpty = (list) => list.length === 0;
const hasPermission = (user, action) => user.permissions.includes(action);
const canEdit = (user) => hasPermission(user, "edit") && !user.locked;

const editor = { permissions: ["edit"], locked: false };
const guest = { permissions: [], locked: false };

console.log(isEmpty([]), hasPermission(editor, "edit"), canEdit(editor), canEdit(guest));
Text
true true true false

The prefixes is, has, can and should mark a value as a yes-or-no question, and the code reads naturally: if (canEdit(user)). Name the positive case, because a negative name makes double negatives: isDisabled with !isDisabled is harder to read than isEnabled. A variable called flag, status or check hides what it means, and visible is better than show, because show sounds like a function.

Acronyms and initialisms

Treat an acronym as a word, so the capitalization of the name stays regular.

JavaScript
const requestUrl = "https://example.test/api";
const userId = 42;

function parseJson(text) {
  return JSON.parse(text);
}

class HttpClient {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
  }
}

console.log(parseJson('{"id":1}').id, new HttpClient(requestUrl).baseUrl, userId);
Text
1 https://example.test/api 42

parseJson and HttpClient read cleanly, where parseJSON and HTTPClient produce runs of capitals that are hard to split, and XMLHTTPRequest in the platform's own library is the cautionary example. A convention that applies everywhere is easier to remember than one with exceptions. Two-letter acronyms are the place where teams disagree, Id versus ID: pick one and make the linter enforce it.

Put units and meaning in the name

A number without a unit is a bug waiting for a caller who assumes the other one.

JavaScript
function wait(timeoutMs) {
  return new Promise((resolve) => setTimeout(resolve, timeoutMs));
}

const DEFAULT_TIMEOUT_MS = 2_000;
const cacheTtlSeconds = 60;
const priceCents = 1999;

console.log(DEFAULT_TIMEOUT_MS / 1000, cacheTtlSeconds * 1000, priceCents / 100);
await wait(1);
Text
2 60000 19.99

timeoutMs states the unit, so no caller passes 2 thinking it means seconds. The same applies to Bytes, Percent, Cents and Px. When a value is a Date, a timestamp or a duration, the name should say which: createdAt is a date, createdTimestamp is a number, and elapsedMs is a duration. Fixing a wrong unit after release costs far more than a longer name.

Private members

Modern JavaScript has real private fields with a # prefix, and older code marked privacy with an underscore.

JavaScript
class Counter {
  #count = 0;
  _legacyCount = 0;

  increment() {
    this.#count += 1;
    this._legacyCount += 1;
    return this.#count;
  }
}

const counter = new Counter();
counter.increment();

console.log(Object.keys(counter));
Text
[ '_legacyCount' ]

The #count field is invisible to Object.keys(), and writing counter.#count outside the class is a SyntaxError, which the engine enforces. The underscore convention only asks callers not to touch the property, and anything can. Use # for new code, and the underscore only in code that must run on engines without private fields.

Files and folders

Pick one rule for file names and apply it everywhere. Kebab-case is safe because file systems differ in case sensitivity: UserAccount.js and useraccount.js are different files on Linux and the same file on a default macOS or Windows setup, and that difference breaks builds in continuous integration.

JavaScript
const toKebab = (text) =>
  text
    .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
    .replace(/[\s_]+/g, "-")
    .toLowerCase();

console.log(toKebab("UserAccount"), toKebab("parseHttpRequest"), toKebab("max_retry count"));
Text
user-account parse-http-request max-retry-count

A file that exports one class can be named after it, as UserAccount.js, and many projects choose to match. What matters is that the rule is written down and a linter or a plugin checks it. Test files take the name of the module plus a marker: user-account.test.js.

Converting between cases at boundaries

Your code is camelCase, and the data you exchange may not be: databases and many APIs use snake_case. Convert at the edge, not inside the code.

JavaScript
const snakeToCamel = (text) => text.replace(/_([a-z0-9])/g, (_, char) => char.toUpperCase());
const camelToSnake = (text) => text.replace(/[A-Z]/g, (char) => `_${char.toLowerCase()}`);

const mapKeys = (object, convert) =>
  Object.fromEntries(Object.entries(object).map(([key, value]) => [convert(key), value]));

const row = { user_id: 7, first_name: "Ada", is_active: true };
const user = mapKeys(row, snakeToCamel);

console.log(user);
console.log(mapKeys(user, camelToSnake));
Text
{ userId: 7, firstName: 'Ada', isActive: true }
{ user_id: 7, first_name: 'Ada', is_active: true }

The conversion happens once, where the row enters the program, and again where the data leaves. Inside, every name follows one convention. The helper handles flat objects only: nested objects need a recursive version, and keys that are acronyms, such as userURL, convert to user_u_r_l unless you handle runs of capitals. We use the same approach for query strings and header names.

Names that collide with globals

Some obvious names are already taken by the platform.

JavaScript
console.log(typeof name, typeof status, typeof length, typeof event, typeof process);
Text
undefined undefined undefined undefined object

In Node.js, only process exists among these. In a browser, window.name, window.status, window.length and window.event exist, and a classic script that declares var name = 42 ends up with the string "42", because the global name property converts whatever it is given to a string. ES modules and let and const avoid the collision. Avoid names such as name, status and event at the top level of a browser script, and keep code in modules. Also avoid shadowing built-ins such as Map, Array and Object, and reserved words such as class, which is why DOM code uses className.

Short names and scope

A name should be as long as its scope is wide. A loop counter in a three-line loop can be i, and a function used across a project needs a precise name.

JavaScript
const totalCents = [199, 250, 600].reduce((sum, cents) => sum + cents, 0);

const matrix = [
  [1, 2],
  [3, 4],
];

for (let row = 0; row < matrix.length; row++) {
  for (let col = 0; col < matrix[row].length; col++) {
    matrix[row][col] *= 2;
  }
}

console.log(totalCents, matrix);
Text
1049 [ [ 2, 4 ], [ 6, 8 ] ]

sum and cents are fine inside a one-line callback. row and col beat i and j when the loop is two deep, since they say which axis is which. Do not abbreviate for brevity in names that live long: usr, cfg and mgr save a few keystrokes and cost every future reader. Well-known abbreviations such as id, url, db and html are fine.

A mistake we hit: two names for one thing

We had customer, client, account and user in one module, and all of them meant the same record at different points of a pipeline. A new developer fixed a bug in the code that used client and missed the three places that used account. The fix was not a rename script but a decision: one word per concept, written in a short glossary in the repository, and a code review check that asks whether a new name is a new concept. A consistent vocabulary is worth more than any single naming rule here.

Enforcing it with a linter

A convention that depends on review comments will drift. ESLint's built-in camelcase rule flags snake_case identifiers, and the @typescript-eslint/naming-convention rule, which also works for JavaScript files in a TypeScript-aware setup, checks each kind of name.

JavaScript
// eslint.config.js
export default [
  {
    rules: {
      camelcase: ["error", { properties: "never", ignoreDestructuring: false }],
      "new-cap": ["error", { capIsNew: false }],
      "id-length": ["warn", { min: 2, exceptions: ["i", "j", "x", "y", "_"] }],
    },
  },
];

The camelcase rule finds first_name, with properties: "never" leaving object property names alone so API keys can stay as they are. new-cap requires a constructor to be capitalized and called with new. id-length warns about one-letter names outside a short list. A formatter such as Prettier does not rename anything, so the linter is the tool for names.

Practical rules we follow

Use camelCase for values, PascalCase for classes, and capitals only for true constants. Start functions with verbs and booleans with is, has, can or should. Treat acronyms as words. Put units in names. Use # for private members. Name files in kebab-case. Convert case at the boundaries. Keep one word for each concept. And let the linter enforce the rest.

Where conventions stop

Conventions make code consistent and do not make names good. A name that follows every rule can still mislead, and a name that breaks one can be the clearest choice in a codebase with its own history. Frameworks add conventions of their own: React requires component names to start with a capital letter, and hook names to start with use. The standard library has its own historical inconsistencies, such as getYear and getFullYear, that you inherit and cannot fix. The reference is in the MDN guide to code style and the ESLint naming rules.

Taggedstyle
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.