Member-only story
Replace Equality Expressions with indexOf() in JavaScript
Simplify your conditions and improve readability
Let’s put ourselves in a fictitious scenario where a message prints only during the hours of 8AM, 10AM, and 2PM. The code block might look something like this…
const d = new Date();
const hour = d.getHours() + 1;if(hour === 8 || hour === 10 || hour === 14) {
console.log("true condition");
}
It’s simple and straightforward, but can get ugly fast. Especially when the variable name or comparison value is longer.
When the overall expression is nothing more than a series of equality checks, piling all the affirmative values into an array and using indexOf() provides cleaner code that is easier to both read and maintain.
Let’s refactor our code using the indexOf() strategy…
const d = new Date();
const hour = d.getHours() + 1;if([8,10,14].indexOf(hour) >= 0) {
console.log("true condition");
}
That’s so much easier to read as long as the reader is familiar with indexOf()!
If you are not familiar with indexOf(), it is a method of both the Array and String class which is a fancy way of saying it comes pre-installed for arrays and strings. If…