Every() and some() in javascript
Daniel Zaltsman
Posted on May 3, 2020
There are times when you get elements back in the form of an array, and need to check a condition for each element. I came upon the every() and some() methods that made it easier to make these checks. Let's take a look at some usecases.
Rotten fruits
We have a basket of fruits and we want to make sure that none of them are rotten. If we find even one fruit that's rotten, we want to throw out the basket(this is not always the case in real life, but let's just go with it).
For both of these methods, we need to pass in a callback function that has a condition to check against each element.
let apples = ["fresh","fresh","fresh","rotten","fresh"]
const isRotten = apples.some(function(apple){
return apple === "rotten"
})
console.log(isRotten)
//expected output: true
This is perfect for this scenario because the some() method short circuits as soon as it hits a truthy value, so finding the rotten apple in the bunch is a perfect use.
But what if instead, we wanted to throw out only the rotten ones and keep the fresh ones? Some() wouldn't work here since it short circuits after the first truthy value. This is where every() comes in. Every() checks all the elements in the array and returns true if every element passes the condition. So in this new scenario, we are only throwing out the bag if every single apple is rotten.
let apples1 = ["rotten","rotten","rotten","rotten","fresh"]
let apples2 = ["rotten","rotten","rotten","rotten","rotten"]
const isRotten1 = apples1.every(function(apple){
return apple === "rotten"
})
const isRotten2 = apples2.every(function(apple){
return apple === "rotten"
})
console.log(isRotten1)
//expected output: false
console.log(isRotten2)
//expected output: true
The first bag of apples has one fresh apple in it, making the bag salvageable and therefore "not rotten". The second bag however, has only rotten apples which output the true value.
Posted on May 3, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.