Follow along with the Exploring JavaScript Array Methods series!
- Exploring Array ForEach
- Exploring Array Map
- Exploring Array Filter
- Exploring Array Reduce
- Exploring Array Some (you’re here)
- Exploring Array Every
- Exploring Array Find
What is Array Some?
Array Some is a method that exists on the Array.prototype
that was introduced in ECMAScript 5 (ES5) and is supported in all modern browsers.
Array Some tells you whether any element in your array passes your test. If one element passes then Array Some returns true
. Some will return false
if no elements pass the test.
As soon as Some finds a true
result, it will short-circuit the loop and continue no more - giving us a performance boost.
Think of Array Some as: “I want to check if any value(s) in my array meets my condition - a yes/no answer”
Free eBook
Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.
- Observables and Async Pipe
- Identity Checking and Performance
- Web Components <ng-template> syntax
- <ng-container> and Observable Composition
- Advanced Rendering Patterns
- Setters and Getters for Styles and Class Bindings
Here’s the syntax for Array Some:
const returnValue = array.some((value, index, array) => {...}, thisArg);
Our returnValue
will contain a Boolean value true
or false
.
As Some returns a Boolean, its result is commonly used in conditional statements.
Array Some syntax deconstructed:
- Some’s first argument is a callback function that exposes these parameters:
value
(the current element)index
(the element’s index - sometimes used with Filter)array
(the array we are looping - rarely used)- Inside the body of the function we need to
return
an expression which will evaluate to a Boolean (true
orfalse
)
- Some’s second argument
thisArg
allows the this context to be changed
See the ECMAScript Array Some specification!
In its simplest form, here is how Some behaves:
const greaterThanOne = [1, 2, 3].some(x => x > 1);
// true
console.log(greaterThanOne);
As our array contains values greater than > 1
, our expression evaluates to true
, and Some returns true
.
Similarly, with an expression that checks if our values are greater than > 3
, Some will return false
:
const greaterThanThree = [1, 2, 3].some(x => x > 3);
// false
console.log(greaterThanThree);
As a performance benefit, Some will short-circuit and stop the loop on a true
test result, otherwise it will continuously loop if results are false
until the loop exits.
Let’s check some examples out.
Using Array Some
Here’s our data structure that we’ll be using Array Some with (take note of the additional promo
property):
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}
];
Let’s use Some to check if any items are in the promo - we should expect to see our Big Slurp '🥤'
trigger Some to return true
:
const isInPromo = items
.some(item => item.promo);
// true
console.log(isInPromo);
Using a ternary statement to calculate our total
- if an item is in the promo we set the price to a flat 600
cents. Otherwise we’ll use Array Reduce to sum the price
properties:
const total = isInPromo ? 600 : items.reduce((prev, next) => prev + next.price, 0);
Our example here is simple, but real enough. You can see how we’ve used the isInPromo
resulting variable as part of a conditional statement - where it’s most commonly used!
Notice how simple Some is, we’re returning item.promo
(either true
or false
) to get a final true
result as one item matched our conditional test.
You can return any type of expression inside Some’s callback function (such as using comparison logic
item.price > 99
).
Give the live Array Some demo a try, you can toggle promo: true
to promo: false
and see the result change:
Bonus: Some-ing without Some
Let’s check out a for...in
loop example that mimics the behaviour of Array Some:
let isInPromo = false;
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.promo) {
isInPromo = true;
break;
}
}
First we set isInPromo
to false
and it’s our job to detect when to set it to true
. We’ll loop the items and if one passes, we set isInPromo
to true
. This is the same behaviour as Some, and if no items match then isInPromo
will remain false
.
Summary
You’ve now learned how to use Array Some to run a test on your array elements. If at least one element in your array, when returned as part of an expression, evaluates to true
then Some will exit the loop and return true
.
If no array elements pass the test Some will return false
.
No array items are returned back to you, Some is exclusively for returning a Boolean result. If you do want items back, Array Map and Array Filter are better methods to use.
If you are serious about your JavaScript skills, your next step is to take a look at my JavaScript courses, they will teach you the full language, the DOM, the advanced stuff and much more!
Free eBook
Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.
- Observables and Async Pipe
- Identity Checking and Performance
- Web Components <ng-template> syntax
- <ng-container> and Observable Composition
- Advanced Rendering Patterns
- Setters and Getters for Styles and Class Bindings
Further tips and tricks:
- Don’t forget to
return
inside your callback, or your values will beundefined
and evaluate tofalse
- avoid undetected bugs! - 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 tothis
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 athisArg
due to arrow functions not having athis
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 Someing!
Go to the next article in Exploring JavaScript Array Methods - Array Every!