JavaScript Coding Guidelines

Build cleaner, more maintainable JavaScript by following practical standards used in real-world teams.

Clean Code
Team Ready
Interview Focused
Want a complete learning path? See How to Learn JavaScript to understand how Tutorials, Exercises, Playground, Projects, Quiz and Interview preparation fit together.

These guidelines are practical recommendations for writing JavaScript that is easier to read, maintain, and review.

Use the comparisons as a starting point. Follow your team's conventions and choose the approach that fits the problem.

Names should reveal what a value or function represents. Follow the same convention throughout a project. Descriptive names make code easier to review and reduce guesswork.

Choose descriptive names

Avoid

javascript

const x = 25;
class car {}
function calc(a, b) { return a + b; }

Prefer

javascript

const userAge = 25;
class CarModel {}
function calculateTotalPrice(price, tax) {
  return price + tax;
}

Use lowerCamelCase for variables and functions, and PascalCase (UpperCamelCase) for classes.

Name shared fixed values consistently

Avoid

javascript

const maxretryattempts = 3;
const taxrate = 0.18;

Prefer

javascript

const MAX_RETRY_ATTEMPTS = 3;
const TAX_RATE = 0.18;
const totalPrice = 500;

UPPER_SNAKE_CASE is a common convention for shared fixed configuration. Local constants usually use lowerCamelCase.

Short names such as i for a small loop can be clear in context. const prevents reassignment of the binding, not mutation of an object or array; use a copy when you need an independent value.

Learn more: Variables and identifiers

Give functions a clear purpose and descriptive names. Extract repeated behavior when it makes the code easier to understand. This avoids duplicated logic and keeps later changes consistent.

Reuse a calculation

Avoid

javascript

console.log(10 * 2);
console.log(20 * 2);
console.log(30 * 2);

Prefer

javascript

const double = number => number * 2;

console.log(double(10));
console.log(double(20));
console.log(double(30));

A named function keeps the calculation in one place. Both versions print the same results.

Keep parameters focused. For several related options, a named object can make a call easier to read. Arrow functions do not have their own this; use a regular function when a method needs its own this.

Learn more: Functions

Choose declarations according to whether the binding needs to be reassigned. Choosing deliberately makes reassignment and mutation easier to reason about.

Prefer const for a stable binding

Avoid

javascript

var userName = "John";
console.log(userName);

Prefer

javascript

const userName = "John";
console.log(userName);

Use const by default and let for reassignment. var is valid JavaScript, but its function scope and hoisting can be surprising.

A const object can still be changed: const user = { name: "Ana" }; user.name = "Lee"; is valid. const only prevents assigning a different value to user.

Learn more: Variables and identifiers

Write statements in a consistent, easy-to-scan style. JavaScript permits several styles, so agree on one with your team. Clear blocks make control flow easier to extend without changing its meaning.

Make branches easy to read

Avoid

javascript

const isReady = true;
if (isReady) console.log("Ready");

Prefer

javascript

const isReady = true;
if (isReady) {
  console.log("Ready");
}

Braces make the intended scope of each branch clear, especially when another statement is added.

Semicolons are a style choice in many situations, not a requirement on every line. Automatic semicolon insertion has edge cases, so follow a consistent formatter and team convention.

Read the error message and location first. Fix the cause instead of suppressing the message. Checking input at a boundary prevents invalid values from producing misleading results.

Validate a number before using it

Avoid

javascript

function double(value) {
  return value * 2;
}
console.log(double("hello"));

Prefer

javascript

function double(value) {
  if (!Number.isFinite(value)) {
    throw new TypeError("Expected a finite number");
  }
  return value * 2;
}
console.log(double(4));

Number.isFinite rejects NaN and infinities as well as non-number values. An explicit error points to the problem.

Learn more: Understanding errors

Warnings identify possible problems, not necessarily failures. Investigate them before deciding whether a change is needed. Separating actionable warnings from intentional exceptions keeps useful diagnostics visible.

Remove unused values

Avoid

javascript

const price = 20;
const unusedDiscount = 5;
console.log(price);

Prefer

javascript

const price = 20;
console.log(price);

Unused declarations make it harder to see which data matters. A linter can flag them during development.

If a warning is intentional, document the reason and suppress only that specific warning according to your project's tooling.

A formatter handles layout; a linter can flag suspicious code. Use the configuration agreed by your project. Consistent layout reduces visual noise so behavior changes stand out in reviews.

Use consistent spacing

Avoid

javascript

function total(a,b){return a+b;}
console.log(total(2,3));

Prefer

javascript

function total(a, b) {
  return a + b;
}
console.log(total(2, 3));

Formatting does not change the result, but consistent indentation and spacing make a function easier to scan.

Configure a formatter such as Prettier and a linter such as ESLint for your project. Run the existing project commands before submitting changes.

Keep values in the smallest scope that needs them. This reduces accidental changes and naming conflicts. Narrow scopes limit where values can be changed or collide.

Keep temporary values local

Avoid

javascript

let total;
function printTotal() {
  total = 10 + 5;
  console.log(total);
}
printTotal();

Prefer

javascript

function printTotal() {
  const total = 10 + 5;
  console.log(total);
}
printTotal();

The second total is available only inside the function. Both examples print the same value.

let and const are block-scoped; var is function-scoped. Modules also provide their own scope. Private class fields restrict access to those fields, not every value used by a class.

Learn more: JavaScript scope

Use names to explain what code does, and comments to explain a useful reason or constraint that the code cannot show. Useful context helps maintainers preserve intent when requirements change.

Explain why, not the obvious

Avoid

javascript

// Set the retry delay to 1000.
const retryDelayMs = 1000;
console.log(retryDelayMs);

Prefer

javascript

// Leave time for the service to recover between retries.
const retryDelayMs = 1000;
console.log(retryDelayMs);

The comment adds context instead of repeating the assignment.

Update or remove comments when behavior changes. Document public APIs and non-obvious constraints when that helps their users.

Use the project's existing tools to catch mistakes, and test important behavior including edge cases. Edge cases reveal assumptions that a typical example alone can miss.

Check a boundary as well as a typical value

Avoid

javascript

function isAdult(age) { return age >= 18; }
console.assert(isAdult(25));

Prefer

javascript

function isAdult(age) { return age >= 18; }
console.assert(isAdult(18));
console.assert(!isAdult(17));

A small assertion catches a regression that a single happy-path check could miss.

Use version control, review changes, and run the project's tests and lint checks. Assertions are a simple illustration; use the project's test runner for automated tests.

Make decisions explicit and keep branches shallow when that improves readability. Shallow control flow helps readers identify the main path.

Return early for an invalid case

Avoid

javascript

function greeting(name) {
  if (name) {
    return "Hello, " + name;
  } else {
    return "Name required";
  }
}
console.log(greeting("Ana"));

Prefer

javascript

function greeting(name) {
  if (!name) return "Name required";
  return "Hello, " + name;
}
console.log(greeting("Ana"));

Both functions return the same messages. The early return leaves the main path less nested.

Choose a clear condition over a clever expression. Multiple valid styles may be appropriate for different situations.

Write code for the next person who will read it. Prefer clear, predictable behavior over clever shortcuts. Explicit ownership helps avoid side effects that surprise callers.

Avoid changing data owned by a caller

Avoid

javascript

const scores = [8, 2, 5];
const sorted = scores.sort((a, b) => a - b);
console.log(scores); // Also changed

Prefer

javascript

const scores = [8, 2, 5];
const sorted = [...scores].sort((a, b) => a - b);
console.log(sorted, scores);

sort changes the original array. Copy it first when the caller still needs the original order.

A spread copy is shallow: nested objects remain shared. Mutation can be appropriate when ownership and the expected behavior are clear.

Learn more: Arrays

Group related files so people can find them. A small project can stay simple; adapt the structure as it grows. A clear layout lowers the effort of finding code as the project grows.

Group files by responsibility

Avoid

text

src/
  app.js
  button.js
  date.js
  form.js

Prefer

text

src/
  app.js
  components/
    button.js
    form.js
  utils/
    date.js

The preferred example makes related interface and utility files easier to locate. This is one possible structure, not a JavaScript requirement.

Use your framework's conventions and keep tests near the code or in the location your project already uses.

Make conversions and comparisons intentional, especially when input comes from a form or URL. Explicit conversions avoid relying on coercion or truthiness that may not match the input's meaning.

Convert input before comparing

Avoid

javascript

const input = "18";
console.log(input == 18); // Coerces the string

Prefer

javascript

const input = "18";
const age = Number(input);
console.log(Number.isFinite(age) && age === 18);

Strict equality does not coerce types. Convert input deliberately and check that it is valid before using it.

Preserve meaningful zero values

Avoid

javascript

const settings = { volume: 0 };
const volume = settings.volume || 50;
console.log(volume); // 50, not 0

Prefer

javascript

const settings = { volume: 0 };
const volume = settings?.volume ?? 50;
console.log(volume); // 0

Use ?? when only null or undefined should trigger a fallback. Unlike ||, it keeps 0, false, and an empty string.

Number("") is 0, so check for empty input first if an empty value should be rejected. Loose equality is valid JavaScript but can hide unexpected conversions.

Compare approaches by the problem they solve. The goal is maintainability, not treating every alternative as invalid. A comparison is useful only when both examples' behavior and tradeoffs are clear.

Name an important condition

Avoid

javascript

const age = 20;
const hasTicket = true;
if (age >= 18 && hasTicket) console.log("Enter");

Prefer

javascript

const age = 20;
const hasTicket = true;
const canEnter = age >= 18 && hasTicket;
if (canEnter) console.log("Enter");

A named condition makes the decision easier to understand. Both examples use the same test.

For an interview, explain your assumptions, choose clear names, and check a typical case and an edge case. Explaining your reasoning and boundaries shows how you approach unfamiliar problems.

Explain behavior with meaningful names

Avoid

javascript

function f(a) { return a.length === 0; }
console.log(f([]));

Prefer

javascript

function isEmpty(items) {
  return items.length === 0;
}
console.log(isEmpty([])); // true
console.log(isEmpty([1])); // false

A descriptive name and boundary checks communicate the intended behavior without relying on a particular coding style.

Discuss time and space costs when relevant, and state what inputs your solution accepts. The Interview section contains dedicated practice questions.

Wait for a result when later work depends on it. Independent operations may run concurrently when that is safe. Running independent work together can reduce latency, while dependency order still matters.

Start independent work together

Avoid

javascript

const delay = value => new Promise(resolve => setTimeout(() => resolve(value), 100));
async function showValues() {
  const first = await delay(1);
  const second = await delay(2);
  return [first, second];
}
showValues().then(console.log);

Prefer

javascript

const delay = value => new Promise(resolve => setTimeout(() => resolve(value), 100));
async function getValues() {
  const first = delay(1);
  const second = delay(2);
  return Promise.all([first, second]);
}
getValues().then(console.log);

Promise.all fulfills when both operations succeed and rejects as soon as one rejects; it does not cancel the other work. Use it only when operations are independent.

Awaiting in a loop is appropriate for dependent steps or rate limits. An async function without await can still intentionally return a promise. Handle rejections at an appropriate boundary.

Learn more: Async and await

Keep DOM updates clear and treat user-provided text as text rather than HTML. This distinction helps keep user-controlled text from being interpreted as markup.

Use textContent for plain text

Avoid

javascript

const message = "<b>Hello</b>";
const output = document.createElement("p");
output.innerHTML = message;
document.body.append(output);

Prefer

javascript

const message = "<b>Hello</b>";
const output = document.createElement("p");
output.textContent = message;
document.body.append(output);

textContent displays text without parsing it as markup. Use HTML insertion only when markup is intended and safely handled.

Batch related updates when measurement shows a benefit. Not every insertion forces a layout. Remove long-lived listeners when they are no longer needed; a detached node is not automatically a leak.

Learn more: DOM tutorial

Handle errors where you can add context or recover. Otherwise let the caller decide what to do. Swallowing a failure hides it; context or propagation lets the right layer respond.

Do not silently discard a parsing failure

Avoid

javascript

try {
  JSON.parse("{");
} catch (error) {
  // Nothing happens.
}

Prefer

javascript

function parseSettings(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    throw new Error("Settings must contain valid JSON: " + error.message);
  }
}
parseSettings("{");

The wrapper adds context and propagates the failure so a caller can handle it.

fetch rejects on network failures, but HTTP errors such as 404 still produce a response. Check response.ok before treating the response as successful.

Learn more: Error handling

Treat input from users and the browser as untrusted. Validate and authorize on the server, even when the browser also validates. Browser-side checks improve feedback but cannot enforce authorization or protect secrets.

Parse data instead of executing it

Avoid

javascript

const userInput = "42"; // Assume this value came from an untrusted source.
const amount = eval(userInput);
console.log(amount);

Prefer

javascript

const userInput = "42";
const amount = Number(userInput);
if (Number.isFinite(amount)) {
  console.log(amount);
}

eval interprets its input as JavaScript, so untrusted input can run arbitrary code in that context. Parse the expected value and validate it instead.

Never put secrets in client-side code or assume browser storage is private from scripts on the page. When HTML is required, use a trusted, maintained sanitizer. Keep dependencies up to date and apply context-appropriate protections on the server.

Measure a real bottleneck before optimizing. Prefer a simple solution until the data shows a need for change. Measurements help target optimizations that affect users without adding needless complexity.

Avoid repeating invariant work

Avoid

javascript

const names = ["Ana", "Lee"];
const query = "A";
const matches = names.filter(name =>
  name.toLowerCase().includes(query.toLowerCase())
);
console.log(matches);

Prefer

javascript

const names = ["Ana", "Lee"];
const query = "A";
const normalizedQuery = query.toLowerCase();
const matches = names.filter(name =>
  name.toLowerCase().includes(normalizedQuery)
);
console.log(matches);

The normalized search term is the same for every item, so it can be prepared once. Measure larger changes in the real application.

Map can be useful for repeated lookups, but no operation is guaranteed to be instant. Measure before optimizing; consider delaying expensive input work, loading large features when needed, and cleaning up timers and long-lived listeners.

They are shared practices for writing readable, maintainable code. They help a team make consistent choices without replacing judgment.

Standards often cover broader team practices; a style guide usually focuses on conventions such as naming and formatting. Teams may use the terms differently.

Shared conventions make code easier to read and review, so a team can focus on behavior and design.

Examples include relying on accidental type coercion, ignoring errors, and changing shared data unexpectedly. Use clear conversions, useful error handling, and focused tests.

Practice explaining your choices, use meaningful names, and test normal and edge cases. A convention is not necessarily a language rule.

All sections expanded. Activate the control to collapse all sections.