javascript array helper - every and some

Javascript Array Helper every() and some()

The every() and some() array helpers are somewhat similar so I will discuss them both in this post. Both of these array helpers return a boolean result.

The purpose of the every() array helper is to execute a function for every array element and test if it meets a certain condition. In the end if all elements meet that condition, true is returned.

The purpose of the some() array helper is to execute a function for every array element and test if it meets a certain condition. In the end if one or more elements meet that condition, true is returned.

A Practical Example

Suppose we have an array of products and we want to test if they all have a category of “Books” or is some have a category of “Books”.

First, let’s look at how we would do this in older ES5 javascript.

var products = [
   { name: 'Checkers', category: 'Toys'},
   { name: 'Harry Potter', category: 'Books'},
   { name: 'iPhone', category: 'Electronics'},
   { name: 'Learn PHP', category: 'Books'}
];
var allProductsBooks = true;
var someProductsBooks = false;

for (var i=0; i<products.length; i++) {
   if (products[i].category != 'Books') {
      allProductsBooks = false;
   }
   else {
      someProductsBooks = true;
   }
}
console.log(allProductsBooks);
console.log(someProductsBooks);

Javascript every() and some() Helper

Here is how the example above would be re-written using the every() and some() helper.

var products = [
    { name: 'Checkers', category: 'Toys'},
    { name: 'Harry Potter', category: 'Books'},
    { name: 'iPhone', category: 'Electronics'},
    { name: 'Learn PHP', category: 'Books'}
];

//do all products have a category of Books
allProductsBooks = products.every(function(product) {
   return product.category === 'Books';
});

//do any products have a category of Books
someProductsBooks = products.some(function(product) {
   return product.category === 'Books';
});

console.log(allProductsBooks);
console.log(someProductsBooks);

Remember the end results of both of these helpers is a boolean value. They every() simply tests if every elements meets a condition and the some() tests if one or more elements meet the condition.

Leave a Reply

Your email address will not be published.