Style Guide and Best Practices
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, notarr2; 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,
constby 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:
| Tool | Job | Typical setup |
|---|---|---|
| Prettier | Formats code consistently | Format on save in the editor; prettier --check in CI |
| ESLint | Finds bugs and risky patterns (no-unused-vars, eqeqeq, no-floating-promises with TypeScript) | eslint.config.js (flat config); errors fail CI |
| EditorConfig | Basic 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
| Kind | Convention | Good | Avoid |
|---|---|---|---|
| Variables, functions | camelCase, descriptive | balanceDue, calculateLateFee | bd, doIt, data2 |
| Booleans | is, has, can, should | isPaid, hasDiscount | paid, flag |
| Functions | Verbs | formatReceipt, loadPayments | receipt, payments |
| Classes | PascalCase nouns | FeeTracker, CardPayment | feeTracker, Manager2 |
| Constants (fixed configuration) | UPPER_SNAKE_CASE | MAX_LATE_FEE, GRACE_DAYS | maxlatefee |
| Collections | Plural | students, paymentsByGrade | studentList2 |
| 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:
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 }));function doReminder(s) {
var f = 0;
if (s.daysLate > 10) { f = (s.daysLate - 10) * 2; if (f > 30) f = 30; }
var t = s.balance + f;
console.log(s.name + ": $" + t.toFixed(2) + " due");
}Srihitha: $97.00 dueEach 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:
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);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
| Practice | Why |
|---|---|
| Use ES modules | Top-level names stay private to each file |
const by default, let when needed, never var | Fewer things can change |
| Pass data as arguments, return results | Dependencies are visible |
| Keep state in one place | One source of truth (see "Managing State") |
| Don't extend built-in prototypes | Array.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
Errorobjects (or subclasses) with useful messages; never throw strings. - Catch errors where you can do something about them; otherwise let them propagate.
- Never leave a
catchempty, 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:
// 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
| Prefer | Over |
|---|---|
=== and !== | == and != |
const, let | var |
| Template literals | String concatenation |
for...of, array methods | Index loops (unless you need the index) |
async/await | Callback nesting, long then chains |
?? for defaults | || (unless replacing every falsy value is intended) |
?. for optional data | Long a && a.b && a.b.c chains |
| Classes or factory functions | Constructor functions with prototype assignments |
toSorted, spread | Mutating 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:
<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>Saved $120 without reloadingHTML 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
| Ask | Look 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:
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]])));var sent = {};
function go(list) {
for (var i = 0; i < list.length; i++) {
if (list[i].balance != 0 && !sent[list[i].id]) {
sendEmail(list[i].email, "Payment reminder for " + list[i].name);
sent[list[i].id] = true;
}
}
}[{ 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.
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
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 }]));['Navika (grade 9)', 'Srihitha (senior)']Key Takeaways
| Practice | Tool or habit |
|---|---|
| Formatting | Prettier |
| Bug patterns | ESLint |
| Readable code | Names, constants, small functions |
| Predictable code | Pure functions, no globals |
| Robust pages | HTML first, progressive enhancement |
Was this tutorial helpful?