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

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 OR operator works pretty much the opposite way, both of the sides have to be false for it to evaluate false:

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.

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

Conclusions

Now that most browsers are based on Chromium, the browser support for ?? is already pretty good. 92.14% globally at the moment of writing this.