JS — A life changing coding trick with anonymous function

Liu Ting Chun
3 min readMar 26, 2021

Anonymous function is one of the most overlooked features in the world of JavaScript. Yet, when used correctly, it can highly improve readability and reduce line of codes. Here I would like to introduce a trick that use anonymous function for assignment, which I find extremely useful.

The Problem

Modern coding practices suggest using const for variables that we know they won’t change. However, it becomes a bit messy when there is condition.

Say we have several conditions and we want to assign different values based on different conditions, we will end up with a long assignment chain like this:

const a = accountType === 'customer' ? ( accountStatus === 'active' ? 'active-customer-account' : 'pending-customer-account' ) : ( accountStatus === 'active' ? 'active-guest-account' : 'pending-guest-account' );

This is bad due to its unreadability. An alternative is to give up using const and use let instead:

let a;
if (accountType === 'customer') {
if (accountStatus === 'active') {
a = 'active-customer-account';
} else {
a = 'pending-customer-account';
}
} else {
if (accountStatus === 'active') {
a = 'active-guest-account';
} else {
a = 'pending-guest-account';
}
}

This is much more readable. However, it is still not ideal as we are losing the information of const. This approach also forces the developers to decapsulate the logic, making “noise” for other developers working together on the same code base.

Some may also suggest using a function:

function computeAccountLevel(accountType, accountStatus) {
if (accountType === 'customer') {
if (accountStatus === 'active') {
return 'active-customer-account';
} else {
return 'pending-customer-account';
}
} else {
if (accountStatus === 'active') {
return 'active-guest-account';
} else {
return 'pending-guest-account';
}
}
}
const a = computeAccountLevel(accountType, accountStatus);

This also works, but the function created is only relevant to a single variable, which is still noise for other developers. Besides, there are even more codes now.

--

--

Liu Ting Chun

Web developer from Hong Kong. Most interested in Angular and Vue. Currently working on a Nuxt.js + NestJS project.