Skip to main content

JavaScript Statement & Expression

JavaScript Identifiers

Written by Updated

JavaScript identifiers are names used to identify variables, functions, objects, classes, and other items in code.

An identifier is a name you give to something: a variable, a function, a class, a parameter, a property. The rules for what makes a valid name are short. The conventions for what makes a good name are what separate code that is easy to work in from code that is not.

Try it

Every declaration here is valid. Run it, then try renaming total to 1total or class and see the error the console gives you.

html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Identifiers</title>
</head>
<body>
<pre id="out"></pre>
<script>
  const total = 3;
  const _draft = "unsaved";
  const $form = document.querySelector("form");   // $ is allowed — jQuery habit
  const maxRetries = 5;
  const MAX_UPLOAD_MB = 10;
  const नाम = "Swapnil";                            // Unicode letters are allowed
  const Total = "different from total";           // case-sensitive

  document.getElementById("out").textContent =
    [total, _draft, $form, maxRetries, MAX_UPLOAD_MB, नाम, Total].join("\n");
</script>
</body>
</html>

The rules

  1. The first character must be a letter, an underscore _, or a dollar sign $. Not a digit.
  2. The rest may be letters, digits, _ or $. No spaces, no hyphens, no dots.
  3. "Letter" means any Unicode letter, so café, नाम and 変数 are legal. Most teams stick to ASCII anyway, for keyboards' sake.
  4. Names are case-sensitive: total, Total and TOTAL are three variables.
  5. Reserved words cannot be used: class, default, new, return, typeof, await (in modules), let and yield (in strict mode), and the rest of the keyword list.
  6. There is no length limit. Longer is not worse; unclear is worse.

The conventions

None of these are enforced by the language. All of them are enforced by any team you will work on, because they carry information: the shape of a name tells you what kind of thing it is before you read its definition.

StyleUsed forExamples
<code>camelCase</code>Variables, functions, parameters, methods, propertiesuserName, fetchLessons(), isLoading
<code>PascalCase</code>Classes, constructors, React components, typesPracticeProblem, new Date(), <LessonCard />
<code>UPPER_SNAKE_CASE</code>Constants that are configuration - fixed for the life of the programMAX_RETRIES, API_BASE_URL
<code>_leadingUnderscore</code>By convention, "internal, do not touch". Old habit - real privacy is #field_cache
<code>#hash</code>Private class fields and methods (actual language feature)#balance, #validate()
<code>$dollar</code>Rare now. jQuery-wrapped elements, Svelte stores, observables in RxJS$button, count$

Naming that reads well

  • Booleans ask a question: isOpen, hasAccess, canSubmit. Never open - is that a verb or a state?
  • Functions are verbs: getUser, renderList, validateEmail. A function called user tells you nothing.
  • Collections are plural: lessons, and each item in a loop is the singular: for (const lesson of lessons).
  • Say the unit: timeoutMs, widthPx, priceInr. A delay of 5 is five what?
  • Avoid abbreviations that are not universal. id, url, max are fine. usrNm, cnt, tmp2 are not.

A realistic example: names that prevent a bug

javascript

// Hard to read — what is d? what unit? which one is the total?
function calc(p, q, d) {
  return p * q * (1 - d / 100);
}

// The same function; the bug in the call is now obvious
function lineTotal(unitPriceInr, quantity, discountPercent) {
  return unitPriceInr * quantity * (1 - discountPercent / 100);
}

lineTotal(499, 2, 0.1);   // ← 0.1 is a fraction, not a percent: the name catches it

Common mistakes

1. Starting with a digit

const 2ndPlace = … is a SyntaxError. Write secondPlace or place2.

2. Hyphens

const user-name = "a" is parsed as user - name, a subtraction, and errors. Kebab-case belongs in CSS class names and file names, not JavaScript identifiers. (Object keys can be anything if quoted: { "user-name": "a" } - but then you must use bracket access.)

3. Reserved words

let class = "btn", const default = 5, function new() {} - all SyntaxErrors. Use className, defaultValue, create. This is why the DOM attribute class is className in JavaScript.

4. Case slips

const userName = …; console.log(username) - ReferenceError, or worse, if a username happens to exist in an outer scope, the wrong value with no error. Consistent camelCase and an editor with autocomplete remove most of these.

5. Shadowing browser globals

In a plain script, var name = "Swapnil" at the top level overwrites window.name - a real property that some browsers coerce to a string. status, top, parent, event, open, close, length are all globals. Use const/let (which do not become window properties) and more specific names.

6. Declaring the same name twice

let count = 1; let count = 2; in the same scope is a SyntaxError. var allowed it silently, which was one of the reasons it was replaced. If you find yourself needing a second count, one of them wants a better name.

7. Names that lie

A variable called userList that holds a Map, a function called getTotal that also saves to the database, an isValid that returns a string. The name is the documentation most people read; keep it truthful when the code changes.

Related chapters