Sknoe / Notes

Principles of Modern JavaScript: Writing Code Humans Can Actually Read

Why modern JavaScript isn't about chasing new syntax—it's about predictability, clear intent, and handling async work without slowing your app down.

5 min read

With AI coding tools in the picture, it can be quick to get a new JavaScript snippet. But then I have the same question I have when reviewing a pull request: will I—and the next developer—understand what this code does six months from now? I have seen such elaborate comments on the PR which sometimes feels just like word salad that tastes bland.That is one reason I went back to these notes.I think this was from a talk on YT.

Every year, JavaScript adds new syntax. If you only chase the latest operators without understanding the mindset behind them, your code doesn't get cleaner—it just gets harder to read.

Whether you are moving from an older SFRA codebase into Storefront Next or reviewing a pull request, good modern JavaScript comes down to one thing: respecting the next developer's working memory.

When you write code, you hold a dozen assumptions in your head. The teammate reading that file six months later doesn't have those assumptions—they only have what is on the screen.

Four principles—plus a few async rules—keep your JavaScript predictable, readable, and easy to maintain.

1. Predictable: make it clear what can change

Predictable code lets the reader know what a variable will hold later without reading every line in between.

Default to const: when a reader sees const taxRate = 0.1, they know that variable binding will not be reassigned. Use let for bindings that need to point to a different value later, such as a running total. Seeing let tells the reader to watch for that reassignment.

When you need a runtime-enforced private class field, #count provides a boundary that a naming convention such as _count does not. Use private fields when encapsulation helps; they are not necessary for every property.

2. Readable: show the operation you intend

A classic for loop works, but for a straightforward transformation followed by a filter, it can take longer to see what the code is doing. Compare a manual loop with array methods:

price-filter.js
// More steps to scan: convert each value, then keep valid prices.
const validPrices = [];
for (let i = 0; i < rawPrices.length; i++) {
const parsed = Number(rawPrices[i]);
if (Number.isFinite(parsed) && parsed > 0) {
validPrices.push(parsed);
}
}
// Clear intent: convert each value, then keep positive finite prices.
const validPricesClean = rawPrices
.map((price) => Number(price))
.filter((price) => Number.isFinite(price) && price > 0);

Each array method communicates a useful contract before you read the callback. For a dense array, map returns a new array with one result per input item. Filter keeps matching values in a new array. Find returns the first matching item or undefined. Neither map nor filter mutates the original array, although a callback can still mutate an object it receives.

The Number.isFinite check matters: Number('not a price') becomes NaN, and Number('Infinity') becomes Infinity. Both should be rejected when you need a positive finite price.

Optional chaining (?.) is helpful when reading a nested value that may be missing, such as order?.shipping?.address?.city. It can reduce repetitive null checks, but it does not validate that an API response has the shape your application expects.

3. Simple: choose clarity over cleverness

Simple does not mean short. A dense one-liner like a.filter(x => x.length < 5 && x !== x.split('').reverse().join('')) may be short, but it is miserable to debug.

True simplicity means choosing one clear tool for the job and naming intermediate values when that makes the steps easier to follow.

Spread (...) and rest (...args) share a visual pattern, but they do different jobs. Spread expands values into an array or call; rest gathers remaining function arguments into an array. Spread is useful for common copying and composition patterns, but it is not a universal replacement for every older array method.

array-copy-and-rest.js
// Copy an array without changing the original array.
const copy = [...items];
// Add items at either end.
const addedEnd = [...items, newItem];
const addedStart = [newItem, ...items];
// Gather any remaining arguments into an array.
function logUserEvents(userId, ...events) {
return events.map((event) => ({ userId, event }));
}

Array and object spread create shallow copies. If an item is itself an object, the copied array still refers to that same nested object. Make the copy depth you need explicit rather than assuming spread performs a deep clone.

4. Flexible: handle asynchronous work deliberately

When an app makes network requests—for product data, SCAPI, or a third-party service—async/await helps keep the JavaScript thread from blocking while the code waits for I/O. It does not make one request finish faster. If three independent requests take about four, two, and three seconds, awaiting them in sequence takes about nine seconds. Promise.all starts the independent operations before waiting for the combined result, so the total wait is roughly the slowest request, assuming the services can handle them concurrently.

dashboard-loader.js
const [profile, orders, saved] = await Promise.all([
fetchUserProfile(userId), // about 4 seconds
fetchUserOrders(userId), // about 2 seconds
fetchSavedItems(userId), // about 3 seconds
]);

For a hanging third-party request, pass an AbortSignal.timeout() signal to fetch. A timeout rejects the client-side fetch with a TimeoutError; it does not guarantee that a server which already received the request stops its work. For the complete Promise.all example and timeout handling, see Async Programming Without the Footguns: Throughput, Promise.all, and Timeouts.

Under the hoodRefactor async code one layer at a timeA low-level helper that becomes asynchronous returns a Promise, so callers must handle or return that Promise.

Looking closer

Starting at a low-level API or data helper and following the Promise through services and route loaders is one practical refactoring approach. It is not the only valid direction. Callers do not all have to use await or add the async keyword: a caller can also return the Promise or attach a handler. The important part is to update each function’s contract and make sure someone handles rejection.

Before merging, check these four questions

Is it predictable? Did you use const by default, and is it clear which bindings change?

Is it readable? Can a teammate tell what a block returns without tracing every index?

Is it simple? Did you choose clarity over a clever one-liner?

Is it flexible? Are independent requests grouped appropriately, and do external fetches have a timeout where the product needs one?

That still matters when AI tools help write the first version. The code can arrive faster; we still need to understand what we are merging.

Did this click?

Tap the bulb if this explanation helped.

Further reading