DEV Community

Jay
Jay

Posted on

One Of The Most Underrated Javascript Method

some() returns a boolean value. It checks whether at least one element in the array passes the test condition supplied to callback function.

Now lets say you have an array of dishes

const buffet = [
 { dish: 'butter chicken' , type: 'non-veg' },
 { dish: 'mutton curry' , type: 'non-veg' },
 { dish: 'meat balls' , type: 'non-veg' },
 { dish: 'butter paneer' , type: 'veg' },
 { dish: 'mutton curry' , type: 'non-veg' },
 { dish: 'meat balls' , type: 'non-veg' },
 { dish: 'mutton curry' , type: 'non-veg' },
 { dish: 'meat balls' , type: 'non-veg' },
 { dish: 'butter paneer' , type: 'veg' },
]

Now let's say you want to check if the buffet has a veg item. Most of the time I have seen people doing something like (including me ... until I came across this method)

let containsVegItem;
buffet.forEach((dish) => {
    if (dish.type === 'veg') {
     containsVegItem = true;
         return
    }
})

Which can be simply done by one line using some() which also gives added performance benefits

buffet.some((dish) => dish.type === 'veg')

Following are some performance benchmarks


console.time('P1');
let containsVegItem;
buffet.forEach((dish) => {
    if (dish.type === 'veg') {
     containsVegItem = true;
         return
    }
})
console.timeEnd('P1')

>>> P1: 0.052978515625ms


console.time('P2');
buffet.some((dish) => dish.type === 'veg')
console.timeEnd('P2');


P2: 0.0400390625ms

Thanks for reading the post so far.
No , there's no promotion at bottom 🤣 ... if you find it useful feel free to hit a like ... and it's ok if you are shy and don't want to 😂

References :-

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

Top comments (0)