Sometimes, we want to shorten conditional statements with JavaScript.
In this article, we’ll look at how to shorten conditional statements with JavaScript.
How to shorten conditional statements with JavaScript?
To shorten conditional statements with JavaScript, we can use the array includes
method.
For instance, instead of writing
if (test.type == 1 || test.type == 2 || test.type == 3 || test.type == 4) {
// do something.
}
We can shorten that to
if ([1, 2, 3, 4].includes(test.type)) {
// do something
}
We check if at least one of 1, 2, 3, and 4 are set as the value of test.type
with
test.type == 1 || test.type == 2 || test.type == 3 || test.type == 4
or
[1, 2, 3, 4].includes(test.type)