Skip to content
Tutorials Center
My learning

Topics

Lesson 121 of 156 ยท Under the Hood

Best Practices and Common Mistakes

Write clean, reliable JavaScript - naming and style conventions, avoiding globals, strict equality, and fixes for floating-point, this, async loop and mutation bugs.

JavaScript is forgiving. It will happily compare a string with a number, let you forget await, or change an array you thought was safe. That flexibility makes it easy to start, and just as easy to write bugs that only appear in production. Experienced developers aren't people who never make these mistakes โ€” they're people who recognize them instantly and have habits that prevent them.

This lesson collects those habits. First you'll see the conventions that make code easy to read and change, then a tour of the mistakes almost every JavaScript developer makes at least once, with a live example and a fix for each. Finally, you'll see how a linter catches many of them before you even run your code.

Write code for the next reader

Code is read far more often than it's written โ€” by teammates, and by you in six months. Readability is not decoration; it's how bugs get spotted.

Naming conventions

JavaScript has a few widely shared conventions. Following them means other developers understand your code at a glance:

What Style Example
variables, functions, methods camelCase cartTotal, loadUser()
classes and constructors PascalCase ShoppingCart, HttpError
true constants (fixed config) UPPER_SNAKE_CASE MAX_RETRIES, API_URL
booleans a question isOpen, hasAccess, canEdit
private class members # prefix #balance
file names kebab-case (common) shopping-cart.js

Beyond the casing, choose names that say what something means, not what type it is. d and data2 say nothing; deliveryDate and unpaidInvoices explain themselves. Functions do things, so start them with a verb: calculateTax(), formatPrice(), isValidEmail().

Small, focused functions

A function that fits on one screen and does one job is easy to name, test and reuse. If you need the word "and" to describe it ("validates the form and saves it and shows a message"), split it. Prefer early returns over deep nesting:

JavaScript
// Hard to follow
function shippingCost(order) {
  if (order) {
    if (order.items.length > 0) {
      if (order.total < 50) {
        return 5;
      } else {
        return 0;
      }
    }
  }
  return 0;
}

// Same logic, flat and readable
function shippingCost(order) {
  if (!order || order.items.length === 0) return 0;
  if (order.total >= 50) return 0;
  return 5;
}

Modern defaults

  • Use const by default and let only when the value must change. Never use var in new code (Variables).
  • Use === and !==, never ==, unless you know exactly why (the only common exception is value == null, which checks for both null and undefined).
  • Use template literals instead of + chains for strings.
  • Use modules instead of global variables. Each module has its own scope, so names can't collide.
  • Format with a tool (Prettier) and stop debating semicolons and quotes by hand. Consistency matters more than the specific choice.

Common mistake 1: loose equality and type coercion

== converts types before comparing, with rules few people remember. === compares without conversion, which is almost always what you mean. The same family of surprises appears whenever JavaScript converts types for you (Type Conversion):

JS Coercion surprises

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The || versus ?? pair deserves extra attention: || treats 0, "" and false as "missing", so a user who sets the volume to 0 gets 50. Use ?? when only null and undefined mean "no value" (Nullish Coalescing and Optional Chaining).

Common mistake 2: trusting decimal math

Numbers are stored in binary floating point, which can't represent most decimal fractions exactly. Small errors appear, and they add up (Numbers):

JS Floating-point money bugs

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For money, store and calculate in the smallest unit (cents) as integers, and format only when displaying (Formatting with Intl). For huge whole numbers beyond Number.MAX_SAFE_INTEGER, use BigInt.

Common mistake 3: losing this

A regular function's this is decided by how it's called, not where it's written (The this Keyword). Passing a method as a callback detaches it from its object:

JS Where did this go?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same bug appears with setTimeout(obj.method, 1000) and button.addEventListener("click", obj.method). Any time you pass obj.method without calling it, ask: "what will this be?"

Common mistake 4: async code inside loops

forEach() doesn't wait for promises. An async callback inside it starts every task and moves on immediately, so code after the loop runs too early. Choose a loop that matches what you want (Async and Await):

JS async inside loops

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Use for...of with await when order matters or each step depends on the last; use Promise.all() when the tasks are independent (Promise Combinators). And never forget the await itself: without it you get a pending promise, not the value, and errors escape your try...catch.

Common mistake 5: mutating shared data

Objects and arrays are passed by reference. Changing one through any variable changes it for every piece of code that holds it. Some built-in methods mutate too, which surprises people:

  • sort(), reverse() and splice() change the original array. Their copying versions โ€” toSorted(), toReversed(), toSpliced() and with() (ES2023) โ€” return a new array instead (Sorting Arrays).
  • Object.assign(target, โ€ฆ) writes into target. Use spread { ...a, ...b } for a new object.
  • Spread and Object.assign copy only one level deep. Use structuredClone() for a full copy (Copying Objects).
JavaScript
const scores = [42, 7, 19];
const ranked = scores.sort((a, b) => b - a);   // sorts `scores` too!
const safe = scores.toSorted((a, b) => a - b); // `scores` untouched

A good rule: functions should not change their arguments. Return a new value and let the caller decide.

Common mistake 6: var and closures in loops

Old code (and old tutorials) use var, which is function-scoped. Every callback in the loop shares one variable, so they all see its final value:

JavaScript
for (var i = 1; i <= 3; i++) {
  setTimeout(() => console.log(i), 0);   // 4, 4, 4
}
for (let i = 1; i <= 3; i++) {
  setTimeout(() => console.log(i), 0);   // 1, 2, 3 โ€” a fresh i per iteration
}

let creates a new binding for every iteration, which is the behavior you expect. This alone is reason enough to never use var (Scope, Closures).

More quick traps

  • Default sort is alphabetical: [10, 9, 1].sort() gives [1, 10, 9]. Always pass a comparator for numbers.
  • typeof null is "object". Check value === null explicitly.
  • parseInt("08px") is 8, but Number("08px") is NaN. Pick the one whose behavior you want, and pass a radix: parseInt(text, 10).
  • Swallowed errors: an empty catch {} hides bugs. At least log the error, or let it propagate (Errors).
  • Comparing objects with === checks identity, not content. Two identical-looking objects are never equal.
  • Implicit globals: assigning to an undeclared name creates a global in sloppy mode. Modules and strict mode turn it into an error.

Let a linter catch it

Many of these mistakes have a pattern a program can spot. A linter reads your code without running it and flags problems. ESLint is the standard for JavaScript; editors show its warnings as you type (Tooling). A minimal flat config looks like this:

JavaScript
// eslint.config.js
import js from "@eslint/js";

export default [
  js.configs.recommended,      // catches undefined variables, unreachable code, etc.
  {
    rules: {
      eqeqeq: "error",         // require === and !==
      "no-var": "error",       // require let/const
      "prefer-const": "warn",  // const when never reassigned
      "no-console": "warn",    // flag leftover console.log calls
    },
  },
];

Some ESLint plugins go further: typescript-eslint adds rules like no-floating-promises, which reports a promise you forgot to await. Combine a linter for correctness, a formatter for style, and tests for behavior (Testing JavaScript), and most of this lesson's bugs never reach your users.

A habit worth building: when you fix a bug, ask "could a lint rule or a test have caught this?" If yes, add it. Each bug you fix that way can never come back quietly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A user sets volume to 0. Which expression keeps 0 instead of falling back to 50?

    ?? only falls back for null and undefined. || also replaces 0, empty strings and false.
  2. 2. What is the safest way to add up prices like 19.99 and 0.1?

    Integers are exact in JavaScript up to 2^53. Working in cents avoids binary floating-point drift.
  3. 3. Why does ids.forEach(async (id) => await save(id)) finish before any save completes?

    forEach ignores return values, including promises. Use for...of with await, or Promise.all(ids.map(save)).
  4. 4. You pass counter.increment to setTimeout. What usually goes wrong?

    A regular method's this depends on how it's called. Wrap it in an arrow function, use bind(), or define it as an arrow class field.
  5. 5. Which call sorts numbers without changing the original array?

    toSorted() returns a new sorted array. sort() sorts in place, and without a comparator it sorts numbers as strings.

Summary

  • Name things for their meaning: camelCase variables, PascalCase classes, question-like booleans, verb-first functions.
  • Keep functions small, return early, use const, ===, template literals and modules.
  • Prefer ?? over || for defaults, and Number.isNaN() for NaN checks.
  • Do money math in integer cents; compare floats with a tolerance.
  • Watch this when passing methods around; don't put async callbacks in forEach.
  • Avoid mutating shared data: use toSorted(), spread, and structuredClone(). Never use var.
  • Let ESLint, a formatter and tests catch mistakes automatically.

Next: JavaScript Performance โ€” measure what's slow, then make pages faster and smoother.