Iterator.prototype.every()
The every()
method of Iterator
instances is similar to Array.prototype.every()
: it tests whether all elements produced by the iterator pass the test implemented by the provided function. It returns a boolean value.
Parameters
-
callbackFn
-
A function to execute for each element produced by the iterator. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:
-
element
-
The current element being processed.
-
index
-
The index of the current element being processed.
Return value
true
if callbackFn
returns a truthy value for every element. Otherwise, false
.
Description
every()
iterates the iterator and invokes the callbackFn
function once for each element. It returns false
immediately if the callback function returns a falsy value. Otherwise, it iterates until the end of the iterator and returns true
. If every()
returns false
, the underlying iterator is closed by calling its return()
method.
The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, every()
returns false
as soon as the first falsy value is found. If the callbackFn
always returns a truthy value, the method never returns.
Using every()
function* fibonacci() {
let current = 1;
let next = 1;
while (true) {
yield current;
[current, next] = [next, current + next];
}
}
const isEven = (x) => x % 2 === 0;
console.log(fibonacci().every(isEven));
const isPositive = (x) => x > 0;
console.log(fibonacci().take(10).every(isPositive));
console.log(fibonacci().every(isPositive));
Calling every()
always closes the underlying iterator, even if the method early-returns. The iterator is never left in a half-way state.
const seq = fibonacci();
console.log(seq.every(isEven));
console.log(seq.next());
Specifications
Browser compatibility
|
Desktop |
Mobile |
Server |
|
Chrome |
Edge |
Firefox |
Opera |
Safari |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
WebView Android |
Deno |
Node.js |
every |
117 |
117 |
No |
103 |
No |
117 |
No |
78 |
No |
No |
117 |
No |
No |