When does two plus two equal two? Never, if we're being truthful
((2 === 2) + (2 === 2)) === 2 //^true
true is always 1 and
false is always zero.
(true - 1) == false // ^true (true - 1) === false // ^false
When might this actually be useful? That's a good question.
A half-baked hypothetical situation: Let's say you're waiting for
x number of functions to resolve to true/false and you care about how many resolve to true.
Let's pretending you've built a quiz. Each function maps to a question on a quiz, and calling that function assesses the question and returns whether or not the user got it right. You care about the total number of right and wrong answers.
You might be able to employ something like this:
// Pretend these are returning right/wrong answers on a quiz const questions = [ () => true, () => true, () => true, () => false, () => false ] const rightAnswers = questions.reduce((acc, question) => acc + question(), 0) //^ 3 right answers
Technically this works because it's doing arithmetic with the boolean responses.
It's definitely a bit of a parlor trick though. You could just as easily do this:
const someRightAnswers = questions.filter((q) => q()).length
Is one appreciably faster or more efficient than the other? I don't know.
It's probably more common to see a scenario like this, where you might only care if some or all of the values are truthy:
const someRightAnswers = questions.some((q) => q()) //^true, because the user did indeed have *some* right answers const allRightAnswers = questions.every((q) => q()) //^false, because the user did not get *all* the answers correct
Fun fact: you can do the same thing in C, Python and PHP. Possibly other languages? Seemingly not in Java, Ruby, Go, Clojure or Haskell.