This page looks best with JavaScript enabled

Shorthand for multiple 'or' condition checks

 ·   ·  ☕ 1 min read

Use this shortcut to do multiple checks in one go.

You have seen an or condition a billion times before, haven’t you?

1
2
3
4
5
6
const fruit = "apple";
let shape;
if (fruit == "apple" || fruit == "orange" || fruit == "water melon") {
  shape = "round";
}
console.log(shape); // round

We use or conditions quite a bit, and there is a way to streamline that code.

1
2
3
4
5
6
const fruit = "apple";
let shape;
if (["apple", "orange", "water melon"].indexOf(fruit) >= 0) {
  shape = "round";
}
console.log(shape); // round

Or, you could use an object.

1
2
3
4
5
6
const fruit = "apple";
let shape;
if ({ apple: true, orange: true, "water melon": true }[fruit] >= 0) {
  shape = "round";
}
console.log(shape); // round

These methods are particularly useful when you have to run your values through a set of validation rules. Instead of using nested if or switch statements, you can use a simple array or object to make your code more readable.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things