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
.sometells us whether a function is true for any element in an array. For example: "are any of these elements2?" Or "are any of these elements an empty string?".sometakes a callback function that runs on every element. If the callback returnstruefor any element,.somereturnstrue.>
[1, 2, 3].some(n => n === 2);Result:
true
>
['a', 'bc', 'def'].some(string => string.length === 0);Result:
false
.somereturnsfalsefor 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:
false
To check for whether every element matches some condition, we use
.every. It works just like.some, but it only returnstrueif our function returnstruefor every element in the array.>
['a', 'bc', 'def'].every(string => string.length > 0);Result:
true
>
[9, 10, 11].every(n => n >= 10);Result:
false
.everyalways returnstruefor 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)istrue, no matter whatfis.[].some(f)isfalse, no matter whatfis.
>
[].every(user => user.name === 'Amir');Result:
true
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
.someto achieve the same result.>
!['a', 'bc', 'def'].some(string => string.length === 0);Result:
true
We can take this one step further and define our own
nonefunction. It's a bit easier to think aboutnonethan![...].some.>
function none(array, callback) {return !array.some(callback);}none(['a', 'bc', 'def'], string => string.length === 0);Result:
true