RxJS icon Launch Deal: Get $100 off the RxJS Kickstart Bundle now!

RxJS Masterclass is here. 2-course bundle - buy now (discount applied at checkout).

days
hours
mins
secs

Exploring Array Some in JavaScript

Mar 26, 2020 8 mins read

JavaScript post
JavaScript icon

Want to level up your JavaScript skills? Who doesn't. Here's what you need to know

Show Me View JavaScript courses

Welcome to the fourth article in this series where you will learn how to use the array prototype method - Some! In this article, you’ll learn how, when and why you should use Some that covers a lot of real-world tips and common pitfalls developers new to Some typically have.

Follow the Array Prototype Series!

You can also follow along with the rest of this series of posts on Array prototype methods:

Not only will you uncover all common practices and syntax you need to use on a daily basis, I’ve also included a lot of hints and tips from over the years writing JavaScript.

Now it’s time to dive into array Some!

What is Some?

Some is a method that exists on the Array.prototype. It provides a way for us to check if at least one element inside an array meets a certain condition. If at least one meets the condition, Some will return either true or false.

Think of it as: “Do Some (or one!) of these values meet my condition? If so, I’d like a yes/no answer.”

Each test (done in the callback function) must return a value that can be evaluated to true or false again each array element, and if one is true then Some will return true once the loop has finished.

This tells us that we could use it for more a conditional check elsewhere in our code by using Some’s return value.

Here’s the syntax for the Some method in JavaScript:

const returnValue = array.some(callback[, thisArg])

Some was introduced in ES5 as a new helper method. I’d encourage you to also read the Array.prototype.some specification.

The first argument is a callback function, which is given three arguments, currentValue, the index and the current array. Some’s callback function is invoked on every item in the array, passing us the item in the array (as well as it’s index as a second argument, if needed).

The second is the (optional) this context, should you wish to pass a new object as a reference to change the execution context.

In its simplest form, here is how Some behaves:

const greaterThanOne = [1, 2, 3].some(x => x > 1);
// true
console.log(greaterThanOne);

const greaterThanFour = [1, 2, 3].some(x => x > 4);
// false
console.log(greaterThanFour);

A nice performance benefit with Some is that it will short-circuit a loop as soon as your first item matches the condition, essentially an automatic break of the loop. This means if you’ve got a huge array, Some won’t pointlessly keep wasting resources looping the rest of your array.

Using the numbers 1, 2 and 3, our first example returns an expression which checks if x (each iteration) is greater than 1. As 2 and 3 are in fact greater, only one has to pass our test. Some will finish the loop and return true as one or more items passed.

The second example demonstrates that no numbers in the array are greater than 4 and therefore we’re presented with false.

Using Some in JavaScript

In this next section, we’ll explore when to use Some and look at some array Some examples in JavaScript. I’ve also thrown in an example of how to Some without Array.prototype.some so you can compare the “old” way of doing things!

When To Use Some

The time to reach for Some is when you need to check if an item in your array matches the criteria you’d like, this is done by passing a conditional test inside the callback. As we’ve covered, Some will return you a Boolean value once it’s finished executing.

Our test could be as simple as - “Are any items in my array in a Promo Deal?”

Items could then be evaluated one-by-one to see if they have a property (or value on a property) that tells us if it’s in a deal!

Generally, Some is not as frequently used as others such as Filter, Map and friends - but you will certainly find use cases for it with your data structures.

As Some accepts a callback function, it’s important to note that this will create new function scope. A traditional Some-ing approach via a for...in will not create new function scope on each iteration.

Array Some example

Let’s look at how we can loop over array elements using Some. Here’s our data structure, a nice array with some objects inside - take note of the promo property and which values are false and true:

const items = [
  { id: '🍔', name: 'Super Burger', price: 399, promo: false },
  { id: '🍟', name: 'Jumbo Fries', price: 199, promo: false },
  { id: '🥤', name: 'Big Slurp', price: 299, promo: true }
];

Here, our Jumbo Fries '🍟' is in the promotion: Buy a drink with your meal and get it all for $6.00. That’d save a few dollars - it would total $8.97 otherwise - a healthy saving!

Let’s use Some to simulate checking whether an item in the customers cart is part of a promotional deal. If it is, then we’ll automatically apply the flat $6.00 total price to that order:

const isInPromo = items.some((item) => item.promo);

// true
console.log(isInPromo);

Yay! We log a Boolean true based on the above data. Notice how simple Some is, we’re simply returning item.promo which is either true or false to get a final true result as one item passed.

I’m also using an arrow function for a clean one-liner (you can use return inside a normal function or long arrow should you wish too).

Our example here is simple, but real enough. It might be that you’d need to do something more fancy such as using comparison !== operators, but apart from that - that’s the gist of Some.

We could also transform the total price of the purchased items to $6.00 and display something more readible for the user:

const isInPromo = items.some((item) => item.promo);

let total;

if (isInPromo) {
  total = 600;
} else {
  total = items.map((item) => item.price).reduce((x, y) => x + y);
}

console.log(`Final Price: ${(total / 100).toFixed(2)}`);

Of course, the example above over-simplifies the process of adding such discounts but the example shows how simple Some can be integrated into your code to perform new conditional actions.

Check it out, try toggling the promo: true to promo: false and see the result change:

That was pretty easy to use Some to detect whether an element in our array was something we wanted and used our returned Boolean to run some conditional logic, if so.

Again, Some is an immutable method so does not touch your original array, nor does it provide you anything back from that array - just a Boolean. I hope this opens up some doors for you in your JavaScript programming!

Bonus: Some-ing without Some

Using a for...in approach, here’s traditionally what one would have to write to mimic “some” without the array Some method. Here’s a side-by-side comparison of the newer array Some approach versus the traditional imperative some-ing:

// Declarative approach: Array.prototype.some
const isInPromoDeclarative = items.some((item) => item.promo);

// Imperative approach: Some-ing
let isInPromoImperative = false;

for (let i = 0; i < items.length; i++) {
  const item = items[i];
  if (item.promo) {
    isInPromoImperative = true;
    break;
  }
}

Both isInPromoDeclarative and isInPromoImperative will contain the same true value if the condition is met. I find breaking out these examples quite nice to explain common patterns and practices and reflect on where API behaviours have been inspired from.

This also demonstrates us the power and flexibility of using Some and other array prototype methods. The code is far smaller, promotes better practices, is easier to read and far more contained.

Summary

Some is a great method for mastering your JavaScript loops and conditional logic by processing their elements. Moving from a traditional for...in loop, the Some method can be introduced to bring a more functional approach and style to your programming.

If you’re enjoying this series, please keep following! To learn more JavaScript practices at this level and comprehensively, I’ve put together some online videos that explore the entire JavaScript language and the DOM - I’d encourage you to check them out if you are serious about JavaScript.

You’ve now learned how to use a Some to run a test on your array. If at least one element in your array when tested results in a true return value on that particular iteration - then Some will exit the loop and return true.

If there are no matches Some will return false. No array items are given back to you, Some is exclusively for returning a Boolean result. If you do want items back, Array Map and Array Filter are perfect tools for the job.

  • Some will test your array values, if one of them evalutes to true then Some will exit and return true - if no tests pass it becomes false
  • Don’t forget to return or your values will be undefined which coerces to false (so an undetected bug could be introduced!)
  • You can access the array you’re looping in the third argument of the callback
  • You can change the this context via a second argument to .some(callback, thisArg) so that any references to this inside your callback point to your object
  • You can use arrow functions with Some but remember that this will be incorrect if you also supply a thisArg due to arrow functions not having a this context
  • Using Some will skip empty array slots as if it were a falsy value
  • You shouldn’t need to in this day and age of evergreen browsers, but use a polyfill for older browsers if necessary

Thanks for reading, happy some-ing!

Love the post? Share it!

Lots of time and effort go into creating all our blogs, resources and demos, we'd love if you'd spare a moment to share this one!