DEV Community

Jay
Jay

Posted on

8 2

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay