Idle JavaScript Observations, Vol. 2: When 2 + 2 = 2

• ~400 words • 2 minute read

When does two plus two equal two? Never, if we're being truthful

But if we want to be deceitful and have fun using addition and booleans in JavaScript we could write something like this that almost suggests this, if you're just taking a glance:

((2 === 2) + (2 === 2)) === 2

That's because JavaScript lets us perform arithmetic with booleans. When you do this true is always 1 and false is always zero.

Here's good example of this in conjunction with demonstrating JavaScript's strict equality operator:

(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.

Filed under: Useless JavaScript.