every() Method – How to Check If Every Element Passes a Test
Whenever you use every() on a JavaScript array, the method does the following:
- It checks if every element in the calling array passes its function argument’s test.
- It returns
true
if all the array’s items pass the test. Otherwise, it returnsfalse
.
Syntax of the every()
Method
every()
accepts two arguments: a “callback function” and a “thisValue.” Here is the syntax:
Argument 1: callback
A function is the first argument accepted by the every()
method. It is a required argument containing the code you want the computer to use to test each item of the calling array.
The callback function returns the Boolean true
(or false
).
In other words, the callback returns true
if all the calling array’s items pass the specified test.
But the callback will return false
if an item fails the test.
Keep in mind that every()
’s function argument accepts three parameters: currentItem
, index
, and an array
.
Parameter 1: currentItem
The currentItem
parameter is required. It represents the current calling array’s item the computer is currently processing.
Parameter 2: index
The index
parameter is optional. It represents the index number of the item the computer is currently processing.
Parameter 3: array
The array
parameter is also optional. It represents the calling array.
Argument 2: thisValue
A thisValue
is the second argument accepted by the every()
method. It is an optional argument representing the value you want to use as the function argument’s this
value.
Suppose you do not provide a second argument. In that case, the computer will use undefined
as the callback function’s this
value.
Example 1: How to Use every()
without a thisValue
Argument
Here is an example of the every()
method without a thisValue
argument:
In the snippet above, we used the every()
method to confirm if every item in the colorsArray
have a length greater than five (5
).
Therefore, the browser returned false
because the array has only one item ("yellow"
) whose length is greater than five (5
).
In other words, not every element in the colorsArray
has a length greater than five (5
).
Example 2: How to Use every()
with a thisValue
Argument
Here is an example of the every()
method with a thisValue
argument:
In the snippet above, we used the every()
method to confirm if every item in the colorsArray
have a length less than five (5
).
We also used the thisValueArray
as the method’s this
value.