some and every
Learn some for any match and every for all matching.
some and every
some asks whether at least one element passes the test; it returns true or false. every instead requires all elements to pass.
Both return a boolean, not an array. Use some to ask 'is there a passing grade in the class?' and every to ask 'did all students pass?'. They short-circuit: some stops at the first true, every at the first false.
every wants all elements
every returns true only when all elements pass; if a single one fails, you get false. Called on an empty array, it returns true, because there is nothing to reject.
This 'vacuous truth' can cause bugs. When you check that every field in a form is filled, you should also check the length to avoid accepting an empty form.
Exercise Did all grades pass?
Check with every whether all grades in grades are 50 or higher. Store the result as allPassed and print it.
Show example solution
const grades = [60, 70, 80, 45];
// are all 50 or higher?
const allPassed = grades.every(grade => grade >= 50);
console.log(allPassed);
Exercise Is there at least one negative?
Check with some whether the temps array has at least one negative value. Store the result as hasFrost and print it.
Show example solution
const temps = [3, -2, 8, 5];
// is there a negative?
const hasFrost = temps.some(temp => temp < 0);
console.log(hasFrost);
Test yourself
-
What is the result of const r = [1,3,5].some(n => n > 4);?
const r = [1, 3, 5].some(n => n > 4);- 5
- [5]
- false
- true
Show answer
true — Correct. Since 5 is greater than 4, some returns true.
-
are all grades 50 or higher?
const grades = [60, 70, 80]; const allPassed = grades.every(g => ____); console.log(allPassed);Show answer
const grades = [60, 70, 80]; const allPassed = grades.every(g => g >= 50); console.log(allPassed); -
Match each scenario to the right method
- is there a negative?
- some
- are all positive?
- every
- first above 100
- find
- list of matching ones
- filter