The unloved array methods of Javascript ? every : some

Tinus Wagner
2 min readApr 12, 2018
pretty much

Whenever I’m bored I randomly select a method or two to investigate, this time I came across the some and every methods. But what’s a practical use case for them? Let’s break it down:

Array.prototype.some

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

Array.prototype.every

The every() method tests whether all elements in the array pass the test implemented by the provided function.

Use Case — Quick validations || sanity checking || testing method

So in my opinion these methods can be quite useful in doing quick and dirty validation checks across collections.

  • Checking if any item in a collection matches a minimum set of criteria.
  • Checking if a collection is valid. Does it contain nil or undefined valyes which could point to issues with code further up the chain.
  • Checking if a collection of relational objects contain at least point of reference.
  • Checking if a collection of relational objects contains any orphaned records, e.g. where a relationship could no longer be returned.
  • Checking if any item in a collection matches an array of values, e.g. do any of my users have [‘Admin’, ‘SuperAdmin’] as their account_type .

And here’s an example to illustrate a few of my points

Couldn’t I just use filter to do this?

Well you sure can and for a very good reason, it’s universally a far more flexible and universally used method. But if your interest lies in in evaluating the quality of an existing collection, as opposed to returning a new collection every and some are definitely far more appropriate tools.

  • some will immediately return out of the method the moment an item in a collection meets some condition.
  • every will immediately return out of the method execution the moment an item in a collection does not meet some condition.

Short and Sweet, thanks for reading!

Let me know if you’ve come across any other nifty use cases for every/some!

…or if you spot a mistake ;)

Sources

--

--