Lessons · TypeScript · some() and every()
Asking a question of every item at once
arr.some(fn) asks 'is at least one true?', arr.every(fn) asks 'are they all true?', in one line.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Form validation, permission checks, 'has every task finished': the yes/no questions about a whole list.
How to think about it
Is the sentence 'is there any...' or 'are all...'? Say it in English first. 'Any' is some(); 'all' is every(). Then write the test for one item and let the method do the loop.
Worked example
const temps = [18, 21, 35, 19];Four readings.
temps.some(t => t > 30);true: stops at the 35.
temps.every(t => t > 15);true: none fails, so it never stops early.
Your turn
Are all names non-empty?
const ok = names.(n => n.length > 0);
Solve one with the tests running
The trap
every() on an empty array is true and some() is false. Sensible once you think about it, surprising the first time.
Practise some() and every() on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.