Execute Program

JavaScript Arrays: Some and Every

Welcome to the Some and Every lesson!

JavaScript arrays' "some" and "every" methods tell us whether a function returns true for some, or every, element of the array.

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • The .some tells us whether a function is true for any element in an array. For example: "are any of these elements 2?" Or "are any of these elements an empty string?"

  • .some takes a callback function that runs on every element. If the callback returns true for any element, .some returns true.

  • >
    [1, 2, 3].some(n => n === 2);
    Result:
    truePass Icon
  • >
    ['a', 'bc', 'def'].some(
    string => string.length === 0);
    Result:
    falsePass Icon
  • .some returns false for an empty array. This makes some sense if we think through it.

  • Suppose that we want to know whether some people are named "Amir". If we ask this about Amir, the answer is yes. If we ask this about Betty, the answer is no. If we ask it about nobody at all, the answer is no; there's no Amir.

  • >
    [].some(user => user.name === 'Amir');
    Result:
    falsePass Icon
  • To check for whether every element matches some condition, we use .every. It works just like .some, but it only returns true if our function returns true for every element in the array.

  • >
    ['a', 'bc', 'def'].every(string => string.length > 0);
    Result:
    truePass Icon
  • >
    [9, 10, 11].every(n => n >= 10);
    Result:
    falsePass Icon
  • .every always returns true for an empty array. One way to remember this is that .every's behavior for empty arrays is the opposite of .some's behavior.

    • [].every(f) is true, no matter what f is.
    • [].some(f) is false, no matter what f is.
  • >
    [].every(user => user.name === 'Amir');
    Result:
    truePass Icon
  • Sometimes we want to confirm that an array doesn't include a specific element. While there's no built-in way to do this, we can negate .some to achieve the same result.

  • >
    !['a', 'bc', 'def'].some(string => string.length === 0);
    Result:
    truePass Icon
  • We can take this one step further and define our own none function. It's a bit easier to think about none than ![...].some.

  • >
    function none(array, callback) {
    return !array.some(callback);
    }
    none(['a', 'bc', 'def'], string => string.length === 0);
    Result:
    truePass Icon