I recently started using array.some()
and at the same time also found array.every()
interesting. It saved time for me, might do the same to you!
We will talk about both methods here.
Array.some()
- It will return
True
if any element matches the required condition. - You would want to use this method in case you want to check if at least one of the elements in the array matches the constraints.
- Array.some() will always return false if the array is empty. But then we ask why so? It is because array.some() returns true if at least one element of an array passes your condition. If the array is empty, none of the elements pass the condition and hence it returns false.
Let's check out Array.some() examples:
- Check if there is a negative number in the array:
- Check if value exists in the array:
- What if there is an empty array and you also need to use
array.some()
? It is possible to do that but note it will always returnFalse
as mentioned before:
Array.every()
- It returns
True
if all the elements in the array match your condition. - You would want to use this method in case you want to check if all the elements in the array match your condition.
- It returns
True
if the array is empty. Then we again ask, hey, why? It is becausearray.every()
returns true if every element of an array passes the condition. If there are no items in the array, every element in the array passes the condition, hence it returns true.
Let's check out Array.every() examples:
- Check if every number in array is negative:
- For empty array it will always return
True
:
Top comments (5)
Very nice explanations, Rakhi, thanks!
You could even use some higher-order functions to create a slick little API for checks that we often use on arrays.
It would be great if you could cover higher order functions in detail.
Let me know what you think about that article @arvindsridharan I would love to have your insight!
Higher-order functions & Why you should use them
Amin ・ Apr 3 ・ 8 min read
Great breakdown! I feel like I never remember these exist 😅
Definitely!!
For the
includes()
andindexOf()
, I agree! I have personally used both methods in my codebase, I might end up writing another post for them.Thanks for sharing Luke.