Nullish Coalescing Operator In JavaScript
A short way of setting default values in JavaScript is using the logical or operator ||. Which returns the left value if the left value is truthy. Otherwise the right value is returned. For example:
function message(contents) { console.log('Message:', String(contents || '(No Message)')); } message(); // Message: (No Message) message('Some contents'); // Message: Some contents
This is supported by all JavaScript environments and browsers even very old ones. Unlike more modern syntax like default function parameters. Note that strings can be created with new String(), which is why the main statement is wrapped in String() above:
message(new String('Some contents')); // Message: Some contents
Anyways, this relies on a value being truthy which is a concept with a bunch of strange exceptions that programmers often miss unless being very careful: https://developer.mozilla.org/en-US/docs/Glossary/Falsy. For example, if I were to pass an empty string in the below:
message(''); // Message: (No Message)
Which is wrong, it should print "Message: ". This is because unlike all other strings an empty string is falsy. So instead of using || more explicity emptyiness checks should be done. So making message work in all cases (assuming the value passed in is always a string):
function message(contents) { console.log('Message:', String((contents || contents === '') ? contents : '(No Message)')); } message(); // Message: (No Message) message('Some contents'); // Message: Some contents message(''); // Message: message(new String()); // Message: message(new String('Some contents')); // Message: Some contents
Which is getting pretty complicated for such a simple operation. Since the above is kind of painful to figure out the danger is there is the temptation to only use || since it works in almost every case. Instead the nullish coalescing operator can be used ??:
function message(contents) { console.log('Message:', String(contents ?? '(No Message)')); }
Currently, this is only fully supported in the latest Chrome, Firefox and a few other environments. Though it will be implemented in other JS environments relatively soon since it is becoming part of the JavaScript standard: https://github.com/tc39/proposal-nullish-coalescing. You can read about the tc39 process here: https://2ality.com/2015/11/tc39-process.html
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2020/nullishOperator.js