JS Conventions

Coding conventions improve readability and consistency. Learn common JavaScript best practices.

On this page

JS Style Guide

A consistent style makes code easier to read, review, and maintain. Most teams follow a style guide and enforce it automatically (formatter + linter).

  • Use consistent indentation (commonly 2 spaces).
  • Prefer single quotes or double quotes consistently (project choice).
  • Use meaningful variable names (camelCase in JavaScript).
  • Keep functions small and focused.
// Good: clear naming, consistent formatting
function formatPrice(value) {
  return value.toFixed(2);
}

JS Best Practices

  • Prefer const, then let: use const by default, let only when reassignment is needed.
  • Use strict equality: prefer === and !== to avoid type coercion surprises.
  • Use early returns: reduce nested code.
  • Use optional chaining: obj?.a?.b prevents crashes when data is missing.
  • Don't mutate data unless needed: prefer immutable patterns for predictable code.
// const-first
const apiUrl = "/api/items";
let page = 1;

// strict equality
console.log(5 === "5"); // false
// Early return
function getDiscount(price, isMember) {
  if (price <= 0) return 0;
  if (!isMember) return 0;
  return price * 0.1;
}
// Optional chaining + nullish coalescing
const city = user?.profile?.city ?? "Unknown";

JS Mistakes

Common mistakes that cause bugs:

  • Accidental globals: assigning to an undeclared variable (strict mode prevents this).
  • Using var: function-scoped and can leak outside blocks.
  • Assuming arrays are objects: typeof [] is "object"; use Array.isArray().
  • Mutating arrays/objects unintentionally: shared references cause side effects.
  • Floating point math: 0.1 + 0.2 is not exactly 0.3.
// Accidental global (in non-strict mode)
function bad() {
  x = 10; // creates global
}
// Reference pitfall
const a = { count: 1 };
const b = a;
b.count = 99;
console.log(a.count); // 99
// Safer copy (modern)
const original = { a: 1, nested: { b: 2 } };
const copy = structuredClone(original);
copy.nested.b = 999;
console.log(original.nested.b); // 2

JS Performance

Most performance issues come from the DOM, unnecessary work, and repeated operations. Start by measuring before optimizing.

  • Avoid repeated DOM queries: cache selectors.
  • Batch DOM updates: update once, not in many small steps.
  • Use event delegation: fewer event listeners.
  • Debounce/throttle: limit expensive handlers (scroll, input, resize).
  • Prefer toSorted/toReversed when you want immutability (when available).
// Cache DOM queries
const list = document.querySelector("#list");
const button = document.querySelector("#load");

button.addEventListener("click", () => {
  list.textContent = "Loading...";
});
// Event delegation
document.querySelector("#list").addEventListener("click", (e) => {
  const item = e.target.closest("li");
  if (!item) return;
  console.log("Clicked:", item.dataset.id);
});
// Debounce (simple)
function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

const onSearch = debounce((value) => {
  console.log("Search:", value);
}, 300);
// Quick measurement
console.time("work");
let sum = 0;
for (let i = 0; i < 100000; i++) sum += i;
console.timeEnd("work");

Next Step

Continue with JS References to use quick lookup pages for syntax, methods, and built-in objects.

JS Conventions Examples (8)