every()

The JavaScript every method will loop over an array and run a provided function for each array item. If the result of the function is true for every element in the array, a Boolean value of true is returned. If any array element fails the test, a false value is returned. The original array is unmodified.

Syntax

const result = array.every(function(currentValue, index, array) {
  // return true if the condition is met for this element, false otherwise
});

Parameters:

  • function: Function that tests each element of the array, taking three possible arguments:
    • currentValue: The current element being processed.
    • index (optional): The index of the current element.
    • array (optional): The original array every() was called upon.

Basic usage

Let's check if all pizza toppings in our list are popular:

const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives'];
const controversialToppings = ['Anchovies', 'Pineapple'];

// Check if ALL toppings are non-controversial
const allToppingsPopular = pizzaToppings.every(topping => {
  return !controversialToppings.includes(topping);
});

console.log(allToppingsPopular);
// Output: true (because none are 'Anchovies' or 'Pineapple')

This example adds pineapple to the toppings array:

// Add a controversial topping
const toppingsWithPineapple = ['Cheese', 'Pepperoni', 'Mushrooms', 'Pineapple'];
const controversialToppings = ['Anchovies', 'Pineapple'];
const allStillPopular = toppingsWithPineapple.every(topping => {
    return !controversialToppings.includes(topping);
});
console.log(allStillPopular);
// Output: false (because 'Pineapple' is present)

Check if all topping names are longer than three characters:

const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives', 'Peppers', 'Sausage'];

// Check if all toppings have names longer than three characters
const longNames = pizzaToppings.every(topping => {
  return topping.length > 5;
});

console.log(longNames);
// Output: true

The following example will check all users are over 18:

const userAges = [25, 31, 19, 49];

// Check if all entered ages are 18 or over
const allAdults = userAges.every(age => age >= 18);
console.log("Are all users adults?", allAdults);
// Output: Are all users adults? true

Using the index parameter

We can access the current index position using the second parameter, let's check if every topping at an even index starts with 'C' or 'M'.

const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives', 'Corn', 'Bacon'];

// Check if every topping at an even index starts with 'C' or 'M'
const checkEvenIndices = pizzaToppings.every((topping, index) => {
  if (index % 2 === 0) { // Only check even index positions
    return topping.startsWith('C') || topping.startsWith('M');
  }
  return true; // Ignore odd index positions
});

console.log(checkEvenIndices);
// Output: true (Index 0: 'Cheese', Index 2: 'Mushrooms', Index 4: 'Corn' all pass)

The function can also be extracted, allowing it to be re-used and improving readability:

const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives'];

const isNotSpicy = (topping) => {
  const spicyToppings = ['Pepperoni', 'Jalapenos', 'Chilli Flakes' ];
  return !spicyToppings.includes(topping);
}

// Check if all toppings are not spicy
const isMild = pizzaToppings.every(isNotSpicy);

console.log(isMild);
// Output: false (because 'Pepperoni' is included in spicyToppings)

Using the array parameter

The third parameter provides a reference/access to the original array. Let's say we want to check if every pizza in the order costs less than $20, and log the original array in the process:

const pizzaOrders = [
  { type: "Margherita", price: 8 },
  { type: "BBQ Chicken", price: 15 },
  { type: "Veggie", price: 9 },
];

const allUnderTwenty = pizzaOrders.every((pizza, index, originalArray) => {
  console.log(`Checking pizza at index ${index}:`, pizza);
  console.log("Full original array:", originalArray);
  return pizza.price < 20;
});

console.log("Are all pizzas under $20?", allUnderTwenty);

We can also use the original array to check if every pizza has a unique price:

const pizzaOrders = [
  { type: "Margherita", price: 8 },
  { type: "BBQ Chicken", price: 15 },
  { type: "Veggie", price: 9 },
];

const allUniquePrices = pizzaOrders.every((pizza, index, originalArray) => {
  // Check if this price appears only once in the array
  const priceCount = originalArray.filter(p => p.price === pizza.price).length;
  console.log(`Pizza: ${pizza.type}, Price: $${pizza.price}, Count: ${priceCount}`);
  return priceCount === 1;
});

console.log("Do all pizzas have unique prices?", allUniquePrices);

Working with objects in arrays

The every method is useful for checking conditions within arrays of objects. This example checks if all pizzas are priced $10 or more, and if all are vegetarian:

const pizzaMenu = [
  { name: 'Margherita', price: 10, isVegetarian: true },
  { name: 'Pepperoni', price: 12, isVegetarian: false },
  { name: 'Vegetarian', price: 13, isVegetarian: true },
  { name: 'Supreme', price: 15, isVegetarian: false }
];

// Check if all pizzas cost $10 or more
const allPricedAtLeast10 = pizzaMenu.every(pizza => pizza.price >= 10);
console.log("Are all pizzas $10 or more?", allPricedAtLeast10);
// Output: Are all pizzas $10 or more? true

// Check if all pizzas are vegetarian
const allVegetarian = pizzaMenu.every(pizza => pizza.isVegetarian);
console.log("Are all pizzas vegetarian?", allVegetarian);
// Output: Are all pizzas vegetarian? false (Pepperoni fails)

Chaining every()

Similar to some, the every method returns a boolean, so chaining after it is uncommon. However, you might use it within the callback of another method such as filter:

const pizzaStores = [
  {
    name: "Store 1",
    pizzas: [
      { name: "Margherita", price: 10, isVegetarian: true },
      { name: "Veggie Supreme", price: 13, isVegetarian: true }
    ]
  },
  {
    name: "Store 2",
    pizzas: [
      { name: "Pepperoni", price: 12, isVegetarian: false },
      { name: "Hawaiian", price: 12, isVegetarian: false }
    ]
  },
   {
    name: "Store 3",
    pizzas: [
      { name: "Cheese", price: 9, isVegetarian: true },
      { name: "Sausage", price: 11, isVegetarian: false }
    ]
  }
];

// Find stores that offer only vegetarian pizzas using filter() and every()
const vegetarianOnlyStores = pizzaStores.filter(store => {
  // Use every() inside the filter callback
  return store.pizzas.every(pizza => pizza.isVegetarian);
});

console.log("Vegetarian only store:", vegetarianOnlyStores.map(store => store.name));
// Output: Vegetarian only store: ["Store 1"]

When to use every() vs. other methods

Use every() when:

  • A true or false return value is required.
  • You need to know if all elements in an array meet a specific condition.
  • Performance is important for large arrays, as every stops as soon as an element fails the test.

Consider using other methods when:

  • You require a new array containing elements that match a condition (use filter()).
  • You need to transform each element (use map()).
  • You need to check if at least one element matches a condition (use some()).
  • You need to find the first element that matches a condition (use find()).
  • You need to perform an action for each element, and modify the original array (use forEach()).
  • You need to accumulate a single value from the array (use reduce()).

Conclusion

The every method is essential for validating that all elements within an array meet certain criteria. It efficiently returns a boolean (true or false) and short-circuits the iteration process as soon as a non-compliant element is found, making it ideal for checks requiring universal adherence to a condition.