Style Guide and Best Practices

Updated · 9 min read
mediumES2026javascriptbest-practicesstyle-guideclean-code

Best practices are habits that make code easier to read, change and trust, especially by people other than the author, including yourself six months later. A style guide writes those habits down so a whole team follows the same conventions. Most formatting choices are settled automatically by tools (Prettier formats, ESLint flags risky patterns), which leaves people free to focus on what tools can't judge: good names, small functions, clear data flow and honest error handling. This lesson collects the practices the rest of the course has used, in one place.

In One Minute

  • Let tools decide formatting: Prettier for layout, ESLint for bug-prone patterns, both run on save and in CI.
  • Names say what things mean: unpaidStudents, not arr2; booleans read as questions (isPaid).
  • Small functions with one job; prefer pure functions that return new values over ones that change shared state.
  • No globals: modules, const by default, strict mode everywhere.
  • Fail loudly and early: validate inputs at the edges, throw meaningful errors, never swallow them.
  • HTML first: build pages that work with plain HTML, then enhance with JavaScript.

Formatting: Let Tools Decide

Arguments about semicolons, quotes and indentation waste time. Pick a formatter, accept its output, and never discuss it again:

ToolJobTypical setup
PrettierFormats code consistentlyFormat on save in the editor; prettier --check in CI
ESLintFinds bugs and risky patterns (no-unused-vars, eqeqeq, no-floating-promises with TypeScript)eslint.config.js (flat config); errors fail CI
EditorConfigBasic settings for every editor (indentation, line endings).editorconfig in the repository

This course follows the most common conventions: 2-space indentation, double quotes, semicolons, trailing commas, and lines under about 100 characters. The professional tooling add-on shows how to configure these tools.

Naming

KindConventionGoodAvoid
Variables, functionscamelCase, descriptivebalanceDue, calculateLateFeebd, doIt, data2
Booleansis, has, can, shouldisPaid, hasDiscountpaid, flag
FunctionsVerbsformatReceipt, loadPaymentsreceipt, payments
ClassesPascalCase nounsFeeTracker, CardPaymentfeeTracker, Manager2
Constants (fixed configuration)UPPER_SNAKE_CASEMAX_LATE_FEE, GRACE_DAYSmaxlatefee
CollectionsPluralstudents, paymentsByGradestudentList2
Private members#name#balance_balance (only a convention)

Include units in names when values could be ambiguous: delayMs, amountCents, timeoutSeconds. A name like amount invites the bug of mixing dollars and cents.

Small, Focused Functions

A function should do one thing that its name describes. Long functions mixing validation, calculation, formatting and output are hard to test and change:

focused.js▶ Try it
const GRACE_DAYS = 10;
const RATE_PER_DAY = 2;
const MAX_LATE_FEE = 30;
 
const lateFee = (daysLate) => Math.min(Math.max(daysLate - GRACE_DAYS, 0) * RATE_PER_DAY, MAX_LATE_FEE);
const amountDue = (student) => student.balance + lateFee(student.daysLate);
const formatUsd = (amount) => new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount);
const reminderLine = (student) => `${student.name}: ${formatUsd(amountDue(student))} due`;
 
console.log(reminderLine({ name: "Srihitha", balance: 85, daysLate: 16 }));
Output
Srihitha: $97.00 due

Each small function can be tested alone, reused (the report page also needs lateFee), and understood in seconds. Named constants replace "magic numbers" whose meaning a reader would have to guess.

Prefer Pure Functions

A pure function returns a result based only on its arguments and changes nothing outside itself. Pure functions are predictable and trivially testable; keep side effects (network, DOM, storage, logging) at the edges of the program:

pure.js▶ Try it
const applyPayment = (account, amount) => ({
  ...account,
  balance: account.balance - amount,
  payments: [...account.payments, amount],
});
 
const before = { name: "Navika", balance: 450, payments: [] };
const after = applyPayment(before, 200);
console.log(before.balance, after.balance, after.payments);
Output
450 250 [200]

The original account is untouched, so there's no question of who changed what, and "undo" means keeping the old value.

Avoid Globals and Shared Mutable State

PracticeWhy
Use ES modulesTop-level names stay private to each file
const by default, let when needed, never varFewer things can change
Pass data as arguments, return resultsDependencies are visible
Keep state in one placeOne source of truth (see "Managing State")
Don't extend built-in prototypesArray.prototype.myHelper can break other code and future standards

Handle Errors Honestly

  • Validate data where it enters the program (forms, files, APIs) and convert it to the right types once.
  • Throw Error objects (or subclasses) with useful messages; never throw strings.
  • Catch errors where you can do something about them; otherwise let them propagate.
  • Never leave a catch empty, and always handle promise rejections.
  • Show users helpful, general messages; log details for developers.

Comments That Explain Why

Code shows what happens. Comments should explain why: the reason for a rule, a non-obvious decision, a link to the requirement:

comments.js
// Bad: repeats the code.
// Add 10 to the days.
const days = daysLate + 10;
 
// Good: explains the reason.
// The school's policy (Fee Handbook 2026, section 4) waives fees for the first 10 days.
const chargeableDays = Math.max(daysLate - GRACE_DAYS, 0);
 
/**
 * Returns the late fee in dollars for a payment that is daysLate days overdue.
 * @param {number} daysLate - Whole days past the due date (0 or more).
 * @returns {number} The fee, at most MAX_LATE_FEE.
 */
function lateFee(daysLate) { /* ... */ }

JSDoc comments (/** ... */) document parameters and return values, and editors show them as hints (TypeScript can even check types from them).

Write Modern JavaScript

PreferOver
=== and !==== and !=
const, letvar
Template literalsString concatenation
for...of, array methodsIndex loops (unless you need the index)
async/awaitCallback nesting, long then chains
?? for defaults|| (unless replacing every falsy value is intended)
?. for optional dataLong a && a.b && a.b.c chains
Classes or factory functionsConstructor functions with prototype assignments
toSorted, spreadMutating shared arrays and objects

HTML First and Progressive Enhancement

Progressive enhancement means building a page so its core works with plain HTML and CSS, then adding JavaScript to make it better. A form that submits to a server works even if a script fails to load; JavaScript then adds instant validation and saving without a reload:

enhance.html
<form id="pay" action="/payments" method="post">
  <label for="amount">Amount</label>
  <input id="amount" name="amount" type="number" min="1" required>
  <button id="save">Save</button>
</form>
<p id="status" role="status"></p>
<script type="module">
  const form = document.querySelector("#pay");
  form.addEventListener("submit", (event) => {
    event.preventDefault();
    const amount = new FormData(form).get("amount");
    document.querySelector("#status").textContent = `Saved $${amount} without reloading`;
    console.log(document.querySelector("#status").textContent);
  });
</script>
Output
Saved $120 without reloading

HTML elements bring behavior for free: <button> is keyboard accessible, <form> validates and submits, <dialog> handles focus, <details> expands and collapses, <input type="date"> gives a date picker. Reach for JavaScript where HTML can't do the job, not before.

A Review Checklist

AskLook for
Can I understand each function from its name?Vague names, functions doing several things
Are inputs validated at the edges?Raw form, URL or API data used directly
Is every error handled or deliberately propagated?Empty catch, missing .catch, floating promises
Is shared data changed in place?Mutation of arguments, state or shared arrays
Is user data inserted as text?innerHTML with variables
Is there a test for the logic?Untested calculations and edge cases
Would it still work without JavaScript, or with a slow network?Missing loading and error states

In Practice

A Fee Tracker function before and after applying these practices:

after.js▶ Try it
const MAX_REMINDERS_PER_DAY = 1;
 
function remindersToSend(students, alreadySentToday) {
  return students
    .filter((s) => s.balance > 0)
    .filter((s) => (alreadySentToday.get(s.id) ?? 0) < MAX_REMINDERS_PER_DAY)
    .map((s) => ({ to: s.email, subject: `Payment reminder for ${s.name}` }));
}
 
const students = [
  { id: 1, name: "Navika", email: "navika@example.com", balance: 0 },
  { id: 2, name: "Srihitha", email: "srihitha@example.com", balance: 85 },
  { id: 3, name: "Advitha", email: "advitha@example.com", balance: 45 },
];
console.log(remindersToSend(students, new Map([[3, 1]])));
Output
[{ to: 'srihitha@example.com', subject: 'Payment reminder for Srihitha' }]

The new version is pure (it decides which reminders to send and returns them; another function sends them), named, uses ===-safe comparisons and ??, and has no global state. In a real project, remindersToSend would be exported from a module and covered by tests.

Common Mistakes

Arguing about formatting. Use Prettier and move on.

Clever one-liners. Clear beats short; name intermediate values.

Functions that both compute and perform side effects. Split deciding from doing.

Comments that repeat the code. Explain why instead, or improve the names.

Practice

Challenge: Refactor this into small named functions and constants, keeping the same output.

practice.js
function x(a) { return a.filter(s => s.g >= 9 && s.g <= 12).map(s => s.n + " (" + (s.g == 12 ? "senior" : "grade " + s.g) + ")"); }
Show solution
practice-solution.js▶ Try it
const HIGH_SCHOOL_GRADES = { first: 9, last: 12 };
 
const isHighSchool = (student) => student.grade >= HIGH_SCHOOL_GRADES.first && student.grade <= HIGH_SCHOOL_GRADES.last;
const gradeLabel = (grade) => (grade === HIGH_SCHOOL_GRADES.last ? "senior" : `grade ${grade}`);
const highSchoolLabels = (students) => students.filter(isHighSchool).map((s) => `${s.name} (${gradeLabel(s.grade)})`);
 
console.log(highSchoolLabels([{ name: "Navika", grade: 9 }, { name: "Srihitha", grade: 12 }, { name: "Zoe", grade: 7 }]));
Output
['Navika (grade 9)', 'Srihitha (senior)']

Quick check: Best practices

3 questions
1What should decide code formatting on a team?
2What is a pure function?
3What should a comment usually explain?

Key Takeaways

PracticeTool or habit
FormattingPrettier
Bug patternsESLint
Readable codeNames, constants, small functions
Predictable codePure functions, no globals
Robust pagesHTML first, progressive enhancement

Was this tutorial helpful?

Lesson 122 of 139