Skip to content

JavaScript Best Practices

Clean code conventions, immutability, modern ES features, and avoiding common footguns.

What you'll learn

  • Preferring const and let over var, and === over ==
  • Immutability with spread and non-mutating array methods
  • Meaningful naming and small, single-purpose functions
  • Consistent error handling and avoiding silent failures
  • Leveraging modern ES features instead of legacy patterns

Concept

Prefer Modern Declarations and Equality

Use const by default and let only when reassignment is necessary — never var. Always compare with === and !== to avoid type-coercion surprises (0 == "" is true, 0 === "" is false). Use ?? (nullish coalescing) for defaults instead of || when 0 or "" are valid values. These three habits alone prevent a large class of bugs.

Embrace Immutability

Prefer non-mutating operations: [...arr] to copy, arr.toSorted() (ES2023) instead of arr.sort(), and spread to update objects ({ ...obj, key: newValue }). Immutability makes state changes predictable, enables cheap equality checks, and is the foundation of React and Redux patterns. When you must mutate, do it in a clearly marked, localized place.

Name Things Well

Names are the primary documentation of your code. Use descriptive, pronounceable names: userEmails not arr, isAuthenticated not flag. Booleans should start with is, has, or can. Functions should be verbs (fetchUsers, calculateTotal). Keep functions small and focused on one task — if a function needs a comment to explain what it does, consider splitting it.

Handle Errors Explicitly

Never swallow errors with an empty catch. Log, rethrow, or recover meaningfully. Throw Error objects (not strings) so stack traces are preserved. Validate inputs at the boundaries of your system and fail fast with clear messages. Use custom error subclasses to distinguish failure types. An unhandled rejection should be a bug you fix, not a pattern you accept.

Use Modern ES Features

Replace legacy patterns with modern equivalents: template literals over concatenation, arrow functions over .bind(this), destructuring over repeated property access, Promise.all over nested callbacks, optional chaining (?.) over manual null checks, and Object.entries / Object.fromEntries for transformations. Modern syntax is not just shorter — it is less error-prone and more expressive.

Lint and Format

Use ESLint and Prettier to enforce conventions automatically. A consistent style across a team reduces cognitive load and prevents bike-shedding in code review. Enable strict mode ('use strict' or ES modules, which are strict by default). Run a linter in your editor and CI so issues are caught before they reach the main branch.

Example

              // BAD: var, ==, mutation, magic names
var x = getData();
if (x == null) x = [];
x.push(transform(item));

// GOOD: const, ===, immutability, clear names
const existingItems = getData() ?? [];
const updatedItems = [...existingItems, transform(item)];

// BAD: nested null checks
const city =
  user && user.address && user.address.city
    ? user.address.city
    : "Unknown";

// GOOD: optional chaining
const cityName = user?.address?.city ?? "Unknown";

// BAD: mutating sort
const sorted = [...data];
sorted.sort((a, b) => a - b);

// GOOD: non-mutating sort (ES2023)
const sortedClean = data.toSorted((a, b) => a - b);

// BAD: silent error swallow
function parse(json) {
  try {
    return JSON.parse(json);
  } catch (e) {
    return null; // hides real bugs
  }
}

// GOOD: explicit error handling with context
function parseSafe(json, context = "input") {
  try {
    return JSON.parse(json);
  } catch (e) {
    throw new Error(`Invalid JSON in ${context}: ${e.message}`);
  }
}

// GOOD: small, named, single-purpose functions
const isActive = (user) => user?.status === "active";
const fullName = (user) => `${user.firstName} ${user.lastName}`.trim();
const toOption = (user) => ({ value: user.id, label: fullName(user) });

const activeOptions = users.filter(isActive).map(toOption);
            

Contrasts bad and good patterns: var vs const/let, == vs ===, mutation vs spread, manual null checks vs optional chaining, in-place sort vs toSorted, silent catch vs explicit error, and small named functions composed into a pipeline.

Try it

  • JSON Formatter

    Format and validate JSON — a boundary where input validation matters most.

  • JSON Validator

    Validate data structures before processing — fail fast with clear errors.

Common mistakes

The mistake

Using var and == in modern code

The fix

Use const by default, let when you need reassignment, and never var. Always use === and !== for comparison. These two changes eliminate a huge class of scope and coercion bugs.

The mistake

Writing large functions that do many things

The fix

Keep functions small and focused on one responsibility. If a function exceeds ~40 lines or needs comments to explain its steps, extract helper functions with descriptive names. Small functions are easier to test, name, and reuse.

Related Cheatsheets

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors