DEV Community

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

Posted on

4 3

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!

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay