JavaScript Arrays: some and every Methods
JavaScript's some
and every
methods inspect the elements of an array to determine whether some or all of their values match criteria you specify. A callback function is passed as the first argument for both of these methods. Each element of the array is passed in turn to the callback function and evaluated according to the criteria established there. The callback function accepts three arguments: the current array element, its index, and the array itself.
The some
and every
methods return true
or false
to indicate whether some or all of the elements in the array they are invoked on meet the criteria established in the callback function.
The every Method
First we will demonstrate the every
method. We want to determine whether all of the values in our example arrays are numeric. We pass a callback function which returns true
if the element passed to it contains a numeric value.[1] We invoke the every
method on two example arrays; one contains some non-numeric values while the second consists only of numbers:
// example array with some non-numeric values
let ar = [2, 27, 33.45, true, 'yes', 0, 3.14];
// pass function that checks if value is number
console.log(ar.every( function(el, i, ar ) {return typeof el === 'number';}));
// returns false
// example array with numbers only
let ar2 = [1, 2, 3, 4.4];
// same function, using arrow function syntax
console.log( ar2.every( el => typeof el === 'number' ) ); // true
When we invoke the every
method on the first example array, it returns false
since it contains some non-numeric values. When we invoke the every
method on the second array, it returns true
since it contains only numeric values.
As soon as one of the elements does not match the criteria, the every
method stops inspecting elements and returns false
.
The some Method
Below we demonstrate using the some
method to check whether any of the elements in our example arrays contain non-numeric values. We pass a callback function that returns true
if the element passed to it contains a value that is not a number. We invoke the some
method on two example arrays; one contains some non-numeric values while the second consists only of numbers:
// example array with some non-numeric values
let ar = [2, 27, 33.45, true, 'yes', 0, 3.14];
// pass function that checks if value is non-numeric
console.log( ar.some( function(el) { return typeof el != 'number'; } ) );
// returns true
// example array with numbers only
let ar2 = [1, 2, 3, 4.4];
// same function, using arrow function syntax
console.log( ar2.some( el => typeof el != 'number' ) ); // false
The some
method returns true
as soon as any element satisfies the criteria established by the callback function. If none of the elements match the criteria, the method returns false
.
- As mentioned above, the callback function accepts three arguments. We only need the first for this example ^