Kilian Valkhof

Building tools that make developers awesome.

A small JavaScript pattern I enjoy using

Javascript, 3 April 2023, 2 minute read

There is a JavaScript pattern that I enjoy using that I don’t see a lot around the web, so I figured it would be worth sharing.

When you have a piece of business logic, frequently that depends on a a certain value being true. An if statement:

if ( status === 'active' ) { … }

This is easy to parse for me and I can quickly see what it does. What often ends up happening though is that the business logic gets a second possibility, for example status being active or status being trialing:

if ( status === 'active' || status === 'trialing') { … }

This is still relatively easy to read but there’s repetition with ‘status’ and I always need a second to think about the difference between || and && to understand the behavior. So whenever I move from checking from one value to more than one, I switch to a different pattern:

if (['active', 'trialing'].includes(status)) { … }

I make an array of all possible values and then use Array.includes() to check if the status is contained in that array.

This pattern comfortably grows to many items and can also more easily be read aloud, helping understanding.

There is no repetition so as a small bonus it’s shorter. It has also helped me learn the difference between includes, contains and has.

Partial string matching

I get a lot of mileage out of the above pattern, but it only works when you’re matching the full string. Sometimes you need to check just the beginning or the end of a string and then .includes() won’t cut it because it only accepts values, not a function.

We don’t want to go back to multiple checks and the repetition that gives so if we need to check for a part of the string we need to change the function we use:

['http://', 'https://', 'file://', 'www.'].some(s => clipboard.startsWith(s)) { … }

Array.some() takes a function and returns a Boolean. It’s a little longer but we’re still not repeating ourselves. A nice benefit is that like includes() it will stop evaluating when it returns true, so we usually don’t have to loop over all the elements.

In the examples above I inlined the array but of course you can also store it in a global variable. That gives you the additional benefit of only instantiating a single array that you can reuse and that lets you update many checks in one go, should the business requirements change.

As I said, I get a lot of use out of this pattern. I hope this helps you recognize when it’ll be useful in your code in the future!

Polypane browser for responsive web development and design Hi, I'm Kilian. I make Polypane, the browser for responsive web development and design. If you're reading this site, that's probably interesting to you. Try it out!