The every() method in JavaScript is used to check if all elements in an array pass a certain condition implemented by a provided function. It returns true if all elements satisfy the condition, otherwise it returns false. This method does not modify the original array.
Syntax
array.every(callback(element, index, array), thisArg);
Parameters
Parameters | Descriptions |
---|---|
callback() | A function to test each element of the array. It takes three arguments: element, index, and array. |
element | The current element being processed in the array. |
index (Optional) | The index of the current element being processed in the array. |
array (Optional) | The array every() was called upon. |
thisArg (Optional) | A value to use as this when executing the callback function. |
Return Value
Return Type | Description |
---|---|
Boolean | true if the callback function returns a truthy value for every array element, otherwise false. |
Example 1: Checking if All Numbers are Positive
This code demonstrates how to use the every() method to check if all numbers in an array are positive.
let numbers = [1, 2, 3, 4, 5]; let allPositive = numbers.every(function(element) { return element > 0; }); console.log(allPositive);
Output:
true
Example 2: Using Arrow Function
This code uses an arrow function to achieve the same result as the previous example.
let numbers = [1, 2, 3, 4, 5]; let allPositive = numbers.every(element => element > 0); console.log(allPositive);
Output:
true
Example 3: Checking if All Strings are Non-Empty
This code demonstrates how to use the every() method to check if all strings in an array are non-empty.
let strings = ["hello", "world", "javascript"]; let allNonEmpty = strings.every(element => element.length > 0); console.log(allNonEmpty);
Output:
true
Example: Using a Provided thisArg
This code demonstrates how to use the every() method with a provided thisArg to access a variable outside the callback function.
let fruits = ["apple", "banana", "cherry"]; let checkLength = function(element) { return element.length === this.length; }; let allSameLength = fruits.every(checkLength, { length: 5 }); console.log(allSameLength);
Output:
true
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1.5 | 9.5 | 3 |