DEV Community

Cover image for some() method explained : JS
Rahul
Rahul

Posted on

some() method explained : JS

The some() method tests whether at least one of the elements in the array passes the test implemented by the provided function. The result of the some() method is a boolean.
Let's see the syntax:-

const new = array.some(( v, i, a) => {
         // return boolean
   });

// newArray - the new array that is returned
// array - the array to run the map function on
// v - the current value being processed
// i - the current index of the value being processed
// a - the original array
Enter fullscreen mode Exit fullscreen mode

The some() method can be thought of like a for loop, that is specifically for checking values. Let's see this example...

cost nums = [11, 12, 13, 14];
let aboveTwenty = false;
for(let i = 0; i < nums.length; i++) {
   if(!aboveTwenty) {
    aboveTwenty = nums[i] > 20;
   }
}
   // aboveTwenty = true; 
Enter fullscreen mode Exit fullscreen mode

This code results in a boolean, the result of the implemented. Yes, it works, but there is an easy to get this.

Now we will rewrite the previous function using the same() method.

const nums = [11, 22, 13, 14]; 
const aboveTwenty = nums.some(value => value > 20); 
      // allBelowTwenty = true;  
Enter fullscreen mode Exit fullscreen mode

*Just see. No loop needed. *

And using the arrow function we have a nice and clean function to create the same array. Because we only use the value, we only pass that to the some() method.

Let's peek to another example:

const nums = [11, 22, 13, 14]; 
const nums2 = [34, -1, 16, 75];

nums.some( value => vaue < 0 ); 
   // returns false

nums2.some( value => vaue < 0 ); 
  // returns true
Enter fullscreen mode Exit fullscreen mode

The first statement returns false because not a single item in the nums array is smaller than 0.


I'm done!
Read more;-

Thanks For Reading! Comment below if anything is going on your mind.

Top comments (0)