Quick JavaScript Tip: the some() method
Matt Sparks
Posted on May 22, 2019
I recently learned of a great JavaScript method I'd never used. It was brought to my attention by Wes Bos. The some()
method is a convenient way to test the values of an array and see if at least one value returns true
. some()
was implemented before ES6 and its support is wide-spread (Internet Explorer 11 supports it).
It's important to note that this method only works on true Array
s. Other iterable types do not implement this method.
Problem: You have an array containing the types of animals your hotel allows. How can you determine if your pet snake, Mr. Slithers, can come along on your trip?
An Older Way:
var animals = ['dogs', 'cats', 'snakes', 'birds', 'pandas'];
var snakesAllowed = false;
for (var i = 0; i < animals.length; i++) {
if(animals[i] === 'snakes') {
snakesAllowed = true;
break;
}
}
console.log(snakesAllowed); // true
Using .some()
:
// Using arrow functions
const animals = ['dogs', 'cats', 'snakes', 'birds', 'pandas'];
const snakesAllowed = animals.some((type) => type === 'snakes');
console.log(snakesAllowed); // true
// Using normal functions
const animals = ['dogs', 'cats', 'snakes', 'birds', 'pandas'];
const snakesAllowed = animals.some(function(type) {
return type === 'snakes';
});
console.log(snakesAllowed); // true
Addendum:
@attacomsian
mentioned in the comments that .includes()
would be a better fit for the problem above. I completely agree. The example above was just to illustrate how .some()
works rather than solve the problem in the most efficient way.
For another example to illustrate .some()
's functionality, let's say we have an array of comic book prices and we want to know if any cost more than $10.
const prices = [5, 8, 11, 10, 25];
const aboveTen = prices.some((price) => price > 10);
console.log(aboveTen); // true
Further reading: MDN web docs
Posted on May 22, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.