30. JavaScript Best Practices

What you will learn

  • Habits that make JavaScript readable and reliable
  • How to avoid the most common bugs
  • Security and accessibility basics
  • A checklist to use before publishing

Why best practices matter

Code is read far more often than it is written, by other people and by you in six months. Small habits keep code easy to understand and hard to break.

1. Use const and let, never var

Start with const, switch to let only when a value must change, and avoid var.

2. Choose clear names

Example

// Hard to read
const d = 86400000;
function f(a) { return a * d; }

// Easy to read
const MS_PER_DAY = 86400000;
function daysToMilliseconds(days) {
  return days * MS_PER_DAY;
}

Use camelCase for variables and functions, and a clear verb for functions: calculateTotal, showError.

3. Keep functions small

A function should do one job. If you need “and” to describe it, split it. Small functions are easier to test, reuse, and fix.

4. Compare with ===

Use === and !==. Convert types on purpose with Number() and String().

5. Avoid magic numbers and repeated code

Give numbers a named constant. If you copy the same lines three times, turn them into a function or loop.

6. Prefer early returns to deep nesting

Example

// Deeply nested
function priceFor(user, item) {
  if (user) {
    if (item) {
      if (item.price > 0) {
        return item.price;
      }
    }
  }
  return 0;
}

// Flatter and clearer
function priceFor(user, item) {
  if (!user || !item) { return 0; }
  if (item.price <= 0) { return 0; }
  return item.price;
}

7. Handle errors and missing values

  • Check that an element exists before using it (if (element)).
  • Wrap risky code, such as JSON.parse and fetch, in try...catch.
  • Check response.ok, and show visitors a friendly message.
  • Never leave an empty catch that hides problems.

8. Keep it secure

  • Use textContent for any text that did not come from you. Avoid innerHTML with outside data.
  • Never use eval() or build code from strings.
  • Never put secret keys or passwords in front-end code.
  • Validate on the server as well. Front-end checks can be bypassed.
  • Do not store sensitive data in localStorage.

9. Keep it accessible

  • Use real <button> and <a> elements, not clickable <div>s.
  • Make sure everything works with the keyboard.
  • Announce changes with role="status" or aria-live, and manage focus when content appears.
  • Respect prefers-reduced-motion for animations.
  • Let the page still work, in a basic way, if JavaScript fails.

10. Keep it fast

  • Load scripts with defer or as modules, and keep files small.
  • Do not run heavy work in a loop on every keystroke. Wait until the visitor pauses (called debouncing).
  • Change the DOM in as few steps as you can.
  • Remove timers and listeners you no longer need.

11. Organise and document

  • Split big programs into modules, each with one purpose.
  • Comment the why, not the obvious what.
  • Be consistent: indentation, quotes, and semicolons. A formatter such as Prettier does this for you, and a linter such as ESLint catches likely mistakes.

12. Test and debug

  • Run your code often, after each small change.
  • Read the Console. Fix the first error first.
  • Test with wrong input: empty fields, huge numbers, odd characters.
  • Try other browsers, a phone, and keyboard-only use.

Before-you-publish checklist

  1. No var, no eval, and no leftover console.log or alert.
  2. All outside data is shown with textContent.
  3. Errors are handled and visitors see friendly messages.
  4. No secrets in the code.
  5. Everything works by keyboard and on a phone.
  6. The Console shows no errors.
  7. Scripts are loaded with defer or as modules.

Do not try to apply every rule at once. Start with const/let, clear names, small functions, ===, and textContent. The rest comes with practice.

Common mistakes

  • Copying code you do not understand.
  • Giant functions and many global variables.
  • Silent failures from empty catch blocks.
  • Trusting the browser for security.
  • Testing only on your own fast computer.

Exercise

Improve this code. Use const, clear names, ===, early returns instead of nesting, and textContent. It must still show many.

Show solution
<p id="demo"></p>

<script>
  const itemCount = 15;

  function describeAmount(count) {
    if (count === 0) { return "none"; }
    if (count > 10) { return "many"; }
    return "some";
  }

  document.getElementById("demo").textContent = describeAmount(itemCount);
</script>

Knowledge check

1. Which keyword should you use by default for variables?

const

2. Why prefer textContent for outside data?

It cannot run HTML or script, which prevents XSS attacks.

3. Should front-end validation replace server validation?

No. It can be bypassed, so the server must check too.

Summary

  • Use const/let, clear names, small functions, and strict comparison.
  • Handle errors, keep secrets out, and show outside data safely.
  • Build for the keyboard, speed, and every browser, and test before publishing.
Scroll to Top