Let’s take a look at the nullish coalescing operator (
Before we begin, a little bit of context…
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression
expr1 ?: expr3returns
||) operator. But Stuart mentioned the nullish coalescing operator, and we wondered what the difference is.
The nullish coalescing operator (
??) only returns its right-hand side operand when its left-hand side operand is
The logical OR operator (
||), on the other hand, returns its right-hand side operand if its left-hand side operand is falsy. This also includes the following values (borrowed from the MDN Web Docs):
Practically speaking, I might use the nullish coalescing operator to assign default values once it’s better supported. It’s a bit stricter and more specific, which is a good thing for me. It makes my code less error-prone.
The use case for this would be if I didn’t want to allow
undefined, but I did want to allow some falsy values. For example…
You can follow the latest browser support information if you’re interested.
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!