JavaScript Array every
Method (Live Playground)
The JavaScript array every
method checks whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
Here's an example:
let numbers = [10, 20, 30, 40, 50];
let check = numbers.every(function (number) {
return number >= 10;
});
console.log(check);
// Expected output: true
In this example, numbers.every(function(number) { return number >= 10; })
checks whether every element in the numbers
array is greater than or equal to 10. Since all elements meet this condition, the output is true
.
Live Playground, Try it Yourself
Here's another example where not every element passes the test:
let numbers = [10, 20, 30, 2, 50];
let check = numbers.every(function (number) {
return number >= 10;
});
console.log(check);
// Expected output: false
In this scenario, the number 2
does not meet the condition, so the every
method returns false
.
Live Playground, Try it Yourself
Remember, the every
method does not change the original array.
Mastering the every
method is important as it's commonly used to check if all elements in an array satisfy a specific condition.