JS — A life changing coding trick with anonymous function
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';
}
}