JavaScript ES6 – Array some method

JavaScript array some() is a method that exists on the Array.prototype and was introduced in ECMAScript and is supported in all modern browsers.

Javascript array some() method check all elements in array, if at least one element passes the condition it will return true, if no element passes the condition the some() method will return false.

Array some() method is great for performance, as soon as it finds a true result it will break the loop and will not continue no more.

Think of JavaScript array some() method as: “I want to check if any value in my array meets my condition. yes/no answer!”

array some() parameters

JavaScript array some() method consists of following parameters:

  • value – value of current element per iteration
  • index – the element index, not common to use

Let’s see an example on how to use JavaScript array some() method:

        
          let arr = [2, 9, 6, 8, 23];
const result = arr.some((value) => value % 2 === 0);
console.log(result);

// OUTPUT
// true        
      

In above example we checking if our array arr has any odd number. If any element in array passes our condition value % 2 === 0 then the array some() breaks out of the loop and will return true.

In this case we can clearly see we have 2 odd numbers. 9 and 23. true is returned as a result.

some() on objects array

We can perform really complex operation using JavaScript array some() method. One of most use cases of JavaScript array some() is using in objects array.

Let’s see an example of some() method for objects:

        
          let foods = [
  {
    name: "Sushi",
    onSale: false
  },
  {
    name: "Chicken",
    onSale: true
  },
  {
    name: "Beef Burger",
    onSale: false
  },
];
const onSale = foods.some((value) => value.onSale);
console.log(onSale)        
      

In example above we are iteration foods object array. Evaluating if any object .onSale property is true.

Our foods object has one property (chicken) set to true. As result we can see there is On Sale food in our object array.

array some() usage and tips

Here are few tips you need to know when considering using JavaScript array some method:

  • If at least one item in array evaluates as true, It will exit the loop and return true
  • If no element in array evaluates as true, it will return false
  • Use some() method only if you need true/false answer
  • Some has great performance unlike other methods
  • Don’t forget to return values, otherwise it will be undefined
  • Array empty slots are skipped

summary

You’ve now learned how to use JavaScript array some() to run a test on your array elements. If at least one element in your array, when returned as part of an expression, evaluates to true() then some() will exit the loop and return true.

If no array elements pass the test some() method will return false.

%d bloggers like this: