DEV Community

JavaScript: Reduce the number of conditional operators used in the expression

K.V.Harish on May 23, 2018

We would have all come across a situation where the number of conditional operators to be used in an expression is more like in the below example. ...
Collapse
 
pichardoj profile image
J. Pichardo

Hi @kvharish , I like what you are trying to do, however wouldn't it be better to make use of the array functions like every or some?, that way you eliminate the need for an additional function:

const firstCondition = true,
  secondCondition = true,
  thirdCondition = true;

const conditionArray = [
  firstCondition,
  secondCondition,
  thirdCondition
];

if (conditionArray.every(contition => condition)) {
  console.log("All the conditions met expectation");
} else {
  console.log("All the conditions did not meet expectation");
}

if (conditionArray.some(condition => condition)) {
  console.log("Atleast one of the conditions met expectation");
} else {
  console.log("None of the conditions met the expectation");
}

And just because I love lazy evaluation you could even turn those conditions into predicates:


const firstPredicate = target => true;
const secondPredicate = target => true;
const thirdPredicate = target => true;

const predicates = [firstPredicate, secondPredicate, thirdPredicate];

conditionArray.every(predicate => predicate(obj))

That way conditions are not evaluated until you need them to.

Regards

Collapse
 
stramel89 profile image
Michael Stramel

Definitely agree using every and some are the way to go. You could simplify further by using Boolean like so, conditionArray.every(Boolean)

Collapse
 
pichardoj profile image
J. Pichardo

Nice, haven't tried it, however, won't it evaluate as true for Boolean being an object?

Collapse
 
kvharish profile image
K.V.Harish

Absolutely we can use every and some.

Collapse
 
teebot profile image
Thibaut Nguyen

Another way to group conditions is to group them in arrays where

for all conditions: [conditionsToCheck].every(x => x)

for at least one: [conditionsToCheck].some(x => x)

Collapse
 
kvharish profile image
K.V.Harish

Yes, we can use it.

More optimized way.