# JavaScript logical operators and the new nullish coalescing operator

The nullish coalescing operator is the newest addition to the JavaScript logical
operator family. It was published in 2020.

There are three different logical operators in JavaScript: AND `&&`, OR `||`,
and then the nullish coalescing operator `??`, which is kind of like the OR
operator, but a bit smarter. For safe property access, the related
[optional chaining operator](/optional-chaining) solves a different problem.

## Recap of logical operators

The AND operator requires both sides of the condition to be the same for it to
evaluate true:

```js
console.log(true && true) // true
console.log(true && false) // false
console.log(false && false) // false
console.log(null && false) // null
console.log(null && true) // null
console.log(0 && false) // 0
console.log(0 && true) // 0
console.log('' && false) // ''
console.log('' && true) // ''
console.log(NaN && false) // NaN
console.log(NaN && true) // NaN
```

The AND operator preserves non-Boolean values and returns them as they are. For
example `null` and `0`, `''`, `NaN`.

The OR operator works pretty much the opposite way, **both of the sides have to
be false for it to evaluate `false`**:

```js
console.log(true || true) // true
console.log(true || false) // true
console.log(false || false) // false
console.log(null || false) // false
console.log(null || true) // true
console.log(0 || false) // false
console.log(0 || true) // true
console.log('' || false) // false
console.log('' || true) // true
console.log(NaN || false) // false
console.log(NaN || true) // true
```

## Nullish coalescing operator

> The nullish coalescing operator (`??`) is a logical operator that returns its
> right-hand side operand when its left-hand side operand is `null` or
> `undefined`, and otherwise returns its left-hand side operand.

The nullish coalescing operator is kind of like OR, but it treats `''`, `0`, and
`NaN` as non-falsy, that’s essentially the only difference between OR and
nullish coalescing.

```js
console.log(true ?? true) // true
console.log(true ?? false) // true
console.log(false ?? false) // false
console.log(null ?? false) // false
console.log(null ?? true) // true
console.log(0 ?? false) // 0
console.log(0 ?? true) // 0
console.log('' ?? false) // ''
console.log('' ?? true) // ''
console.log(NaN ?? false) // NaN
console.log(NaN ?? true) // NaN
```

`??` should be used if `''`, `0`, or `NaN` are considered to be valid values.

## Conclusions

Now that most browsers are based on Chromium, the browser support for `??` is
already pretty good.
[92.14% globally](https://caniuse.com/mdn-javascript_operators_nullish_coalescing)
at the moment of writing this.
