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.
- It will return
Trueif 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.
- 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 return
Falseas mentioned before:
- It returns
Trueif 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
Trueif the array is empty. Then we again ask, hey, why? It is because
array.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.
- Check if every number in array is negative:
- For empty array it will always return