for (const user of users) {
if (user.isActive) {
activeUsersInContext.push(user);
}
}
vs
for (let i = 0; i < users.length; i++) {
const u = users[i];
if (u.a) ctx.push(u);
}
why this pick
Code gets read way more than it gets written. A clear name is one less comment to write.
Clean coding
function checkout(cart) {
let total = 0;
for (const item of cart.items) {
total += item.price * item.qty;
}
if (cart.coupon) total *= 1 - cart.coupon.pct;
if (total > 100) total -= 10;
return Math.round(total * 100) / 100;
}
vs
My pick
const subtotal = (items) =>
items.reduce((s, i) => s + i.price * i.qty, 0);
const withCoupon = (t, c) => c ? t * (1 - c.pct) : t;
const withFreeShip = (t) => t > 100 ? t - 10 : t;
const checkout = (cart) =>
round2(withFreeShip(withCoupon(subtotal(cart.items), cart.coupon)));
why this pick
Each step is testable, named, swappable on its own. The pipeline tells the story without you having to add a paragraph.
Code verbosity
My pick
const slug = (s) =>
s.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
function useCurrentUser() {
return useQuery({ queryKey: ["me"], queryFn: fetchMe });
}
function Page() {
const { data } = useCurrentUser();
return <Profile user={data} />;
}
why this pick
Split the what from the how. The component stays readable, the logic becomes reusable and testable. Everybody wins!
Error handling
My pick
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
async function loadUser(id): Promise<Result<User>> {
const res = await fetch(`/users/${id}`);
if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };
return { ok: true, value: await res.json() };
}
vs
async function loadUser(id) {
try {
const res = await fetch(`/users/${id}`);
if (!res.ok) throw new Error("HTTP " + res.status);
return await res.json();
} catch (e) {
console.error(e);
return null;
}
}
why this pick
The caller literally can't forget a failure exists. The compiler reminds them, so I don't have to at 3am in production.
Comments
// Loop over invoices
for (const inv of invoices) {
// Add tax
inv.total = inv.subtotal * 1.15;
// Push to result
result.push(inv);
}
vs
My pick
// Quebec invoices always include GST+QST combined (14.975%);
// we round to 1.15 by policy — see finance/spec.md §3.
for (const inv of invoices) {
inv.total = inv.subtotal * 1.15;
result.push(inv);
}
why this pick
The code already says what it does. A comment should say why it exists, not paraphrase the line below it.