DEV Community

Cover image for Simple trick to use Array.includes() for conditionals
James Won
James Won

Posted on

Simple trick to use Array.includes() for conditionals

This is a quick post on a sweet little trick I learned.

Conditionals

When writing a conditional you can sometimes write code like this to check for the value of a variable:

myVariable === 'abc' || myVariable === 'cba' || myVariable === 'xyz'

Totally nothing wrong with this. But this is a bit verbose, especially as the list gets longer. Also imagine this inside of a if statement or a ternary.

if (myVariable === 'abc' || myVariable === 'cba' || myVariable === 'xyz') return result

// OR

const value = myVariable === 'abc' || myVariable === 'cba' || myVariable === 'xyz' ? 'a' : 'b'
Enter fullscreen mode Exit fullscreen mode

The code is not complicated but amongst other code this can get annoying pretty fast.

This is something I did a lot until recently, without giving it a second thought.

.includes() a better way

A colleague of mine recently pointed out that you can use Array.Prototype.includes to write the same conditionals in a much simpler way

eg.

['abc', 'cba', 'xyz'].includes(a)
Enter fullscreen mode Exit fullscreen mode

Nice and short and totally readable!

ES7

When I got this feedback I got a bit curious as I didn't recall ever using .includes before. I mean I do use Array.Prototype methods like .map, .reduce, .filter frequently after all.

After digging I found that this method is relatively new, introduced in ES7 (ECMAScript 2016).

This explains why I hadn't used it before - another reminder to check out the MDN docs more often!

Takeaways

So there you have it. TL;DR Use .includes() for conditionals that need to check a variable in multiple ways, its much more readable!

Top comments (0)