Replace Equality Expressions with indexOf() in JavaScript

Simplify your conditions and improve readability

Replace Equality Expressions with indexOf() in JavaScript
Photo by Chase Clark on Unsplash

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 found, the method will return the position of the search value; otherwise, the value -1 will be returned.console.log([4,7,2,9,2].indexOf(1)); // -1
console.log([4,7,2,9,2].indexOf(7)); // 1
console.log([4,7,2,9,2].indexOf(2)); // 2
console.log([4,7,2,9,2].indexOf(9)); // 3
console.log([4,7,2,9,2].indexOf(4)); // -0

Notice how indexOf() returns the first occurrence (from the left). Going back to our original refactor, we use the comparison >= 0 because that functionally translates to “the value was found”.


I hope you liked this article! Subscribe to be notified when I publish new articles or even better, support me by joining the Medium community as a paid subscriber.

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe