---
title: Idle JavaScript Observations, Vol. 2: When 2 + 2 = 2
author: George Mandis <george@mand.is>
date: 2021-11-16
description: Let&#39;s show how 2 + 2 = 2 in JavaScript... Kind of.
tags: post, post, useless, javascript
---

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:

```javascript
((2 === 2) + (2 === 2)) === 2
//^true
```

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:

```javascript
(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:

```javascript
// 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:

```javascript
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:

```javascript
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.

&rarr; **Filed under**:  [Useless JavaScript](/useless-javascript).