Table of Contents
What every() Does
Returns true or false: a plain boolean, not an item and not an index.
All items must pass: one failure is enough to make the result false.
Stops at the first failure: once an item fails, the rest never get checked.
Leaves the original array alone: it only reads through it.
let numbers = [2, 4, 6, 8]; let allEven = numbers.every(n => n % 2 === 0); console.log(allEven); // true
Syntax and Parameters
array.every(function (item, index, array) {
return condition;
});
item: the current element being checked.
index: its position in the array.
array: the full array. You'll rarely need it.
The function must return true or false: that decides whether the item passes.
Practical Examples
Checking that every score is a pass:let scores = [72, 85, 90, 65]; console.log(scores.every(score => score >= 50)); // trueChecking that all form fields are filled:
let fields = ["Vi", "vi@email.com", "Bangalore"]; console.log(fields.every(field => field !== "")); // trueChecking that every task is done:
let tasks = [
{ title: "Study", done: true },
{ title: "Gym", done: false }
];
console.log(tasks.every(task => task.done)); // false
Things to Remember
It stops early: the moment one item fails, it returns false without checking the rest.
let numbers = [2, 4, 5, 8, 10];
numbers.every(n => {
console.log(`Checking ${n}`);
return n % 2 === 0;
});
// Checking 2
// Checking 4
// Checking 5
An empty array always gives true: with nothing to fail the test, it passes by default. This surprises a lot of people.
console.log([].every(n => n > 100)); // trueGuard against empty arrays when it matters: if "no items" should count as a failure, check the length too.
let items = []; let allValid = items.length > 0 && items.every(i => i.valid);
Common Mistakes
Forgetting the empty array case: [].every(...) is true, which can hide bugs in validation code.
Forgetting to return a value: with curly braces, you need an explicit return, otherwise nothing passes and the result is false.
Using it to find the failing item: every() only says yes or no. Use find() with the opposite condition to get the item that failed.
Conclusion
Frequently Asked Questions (FAQs)
Always true, because there's no item that could fail the test.
2.What's the difference between every() and some()?
3.Does every() change the original array?every() needs all items to pass. some() needs only one.
No. It only reads through the array.
0 Comments