Lesson 40 - JavaScript Array Method – every()
The every()
method checks whether all elements in an array satisfy a given condition. It returns true
if all elements pass the test; otherwise, it returns false
.
Explanation
- It runs a callback function on every element in the array.
- If all elements satisfy the condition, it returns
true
. - If at least one element fails, it returns
false
. - It does not modify the original array.
Syntax
let result = array.every((element, index, array) => {
return condition;
});
element
: The current item being processed.index
(optional): The index of the current element.array
(optional): The array being processed.
Example 1: Checking If All Numbers Are Positive
let numbers = [2, 4, 6, 8];
let allPositive = numbers.every(num => num > 0);
console.log(allPositive); // Output: true
- All numbers are positive, so it returns
true
.
Example 2: Checking If All Words Are Shorter Than 6 Letters
let words = ["apple", "banana", "kiwi"];
let allShortWords = words.every(word => word.length < 6);
console.log(allShortWords); // Output: false
- "banana" is longer than 6 letters, so it returns
false
.
Example 3: Checking an Empty Array
let emptyArray = [];
let checkEmpty = emptyArray.every(num => num > 0);
console.log(checkEmpty); // Output: true
- The method returns
true
for an empty array because there are no elements to check.
Try Your Hand
Steps:
-
Create a File:
- Name it
lesson40-every.html
.
- Name it
-
Write the Code:
-
Copy the following:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 42 - every() Method</title> </head> <body> <h2>Checking If All Numbers Are Even</h2> <p id="result"></p> <script> let numbers = [2, 4, 6, 8, 10]; let allEven = numbers.every(num => num % 2 === 0); document.getElementById("result").textContent = "All numbers are even: " + allEven; </script> </body> </html>
-
-
Save the File.
-
Open it in a Browser to Check If All Numbers Are Even.
Experiment
- Check if all numbers in an array are greater than 10.
- Verify if all elements in an array of booleans are
true
. - Ensure all students in an array have passed an exam (e.g., score >= 50).
Key Takeaways
every()
checks all elements against a condition.- If all match, it returns
true
; otherwise, it returnsfalse
. - It stops checking as soon as it finds a failure.
- Returns
true
for an empty array.