Multiple conditions in JavaScript

Justin Lee
2 min readAug 18, 2021

--

How do you handle multiple conditions in the if statement?

Do you use && and || to handle it?

Those are very useful operators to check whether the condition is true.

However, life is not that easy. When you encountered much much longer conditions like below?

if(type === 'normal' && member.type === 'vip') || (type === 'not normal' && member.type === 'eco') {...} 

what if there are much more complex conditions in a single if statement?

Are you going to keep it that way?

Let me introduce alternative ways to check or and and .

Step 1. — Avoid human errors

//models.js
export const MEMBER_TYPE = {
ECO = 'eco',
VIP = 'VIP',
{...},
}
export const TYPE = {
NORMAL = 'normal',
NOT_NORMAL = 'not normal',
}

Step 2. — Make an Array

//implementation.js
import {MEMBER_TYPE, TYPE} from 'models.js'
const conditions = [
condition === TYPE.NORMAL && mem_type === MEMBER_TYPE.VIP,
condition === TYPE.NOT_NORMAL && mem_type === MEMBER_TYPE.ECO,
{...}
];
//if you want the condition to be `or`
conditions.includes(true);
//if you want the condition to be `and`
!conditions.includes(false);

Step 3. — Make this to be more functional

//implementation.js
import {MEMBER_TYPE, TYPE} from 'models.js'
function isORCondition (condition, mem_type){const conditions = [
condition === TYPE.NORMAL && mem_type === MEMBER_TYPE.VIP,
condition === TYPE.NOT_NORMAL && mem_type === MEMBER_TYPE.ECO,
{...}
];
return conditions.includes(true);}{...}if(isORCondition('normal', 'vip')){...}

By following these three steps, you can prevent human errors, and also enhancing readability.

--

--

Justin Lee
Justin Lee

Written by Justin Lee

Software Engineer at Loblaw Digital

Responses (5)