Writing Readable JS Code
May 19, 2019

Some of the below examples use a utility library such as lodash.

Named booleans

// bad
const person = true;
// good
const isPerson = true;

Named parameters

// bad
refresh(true);
// good
const isLive = true;
refresh(isLive);

Safety

// bad
if (typeof engine.outputs[source.node] !== "undefined" &&
    typeof engine.outputs[source.node][source.port] !== "undefined") {
    // do stuff
}
// good
if (_.get(engine, ["outputs", source.node, source.port], false) {
    // do stuff
}

Named chains

// bad
Api.getUserNotifications()
    .then(function(notifications) {
        return _.filter(notifications, {seen: false})
    });
// good
function filterUnseenNotificaitons(notifications) {
    return _.filter(notifications, {seen: false})
}
Api.getUserNotifications()
    .then(filterUnseenNotificaitons);

Minimalism

// bad
function handleExecution(side) {
    if (side === "sells") {
        Api.executeSells().then(refreshSells);
    }
    if (side === "buys") {
        Api.executeBuys().then(refreshBuys);
    }
}
handleExecution("sells");
// good
Api.executeSells().then(refreshSells);
Get updates