In this section, we will learn what the every() method is and how to use it in JavaScript.
JavaScript Arrays every() Method
The `every()` method is used to run a test on every element in an array. Basically, when we want to exam all the elements in an array, we can use this method.
Array every() Syntax:
array.every(function(currentValue, index, arr), thisValue)
Array every() Method Parameters:
The `every()` method takes two arguments.
The first argument is a reference to a function. For each element in the target array, the `every()` method will call that function.
For each call to this function, three arguments will be passed as well:
- The first argument is the element of the array that the function is called for.
- The second argument is the index number of this element.
- The third argument is a reference to the target array itself.
Inside this function we define a set of instructions to exam each element and at the end, this function should return either the value `true` or `false` as a result of the examination.
Other than the function, the `every()` method takes a second argument as well. This second argument, which is optional, is a reference to an object that will bind to the `this` keyword in the target function that we passed as the first argument.
Array every() Method Return Value:
The final result of the `every()` method is a Boolean value. If the result of all the elements in the function was `true`, the final result of the `every()` method becomes also `true`. Otherwise, even if the result of calling the function for one element returned `false` the final result for the `every()` method will be `false` as well.
Example: Checking All Elements in JavaScript Array
const arr = ["Tesla","Google","Microsoft","Amazon","Facebook","Twitter"]; function eve(value, index, arr){ return typeof value =="string"?true: false; } const final = arr.every(eve); console.log(final);
Output:
true
Example: using JavaScript every() method in JavaScript
const arr = ["Tesla","Google","Microsoft",2,3,4,"Amazon","Facebook","Twitter"]; function eve(value, index, arr){ return typeof value =="string"?true: false; } const final = arr.every(eve); console.log(final);
Output:
false