clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

JavaScript logical operators and the new nullish coalescing operator

Filed under: JavaScript— Tagged with: es2020

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.

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

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

?? 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 at the moment of writing this.

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!