There's quite a few JavaScript idioms that coerce between types and similar things.
! can convert anything falsey to boolean true, !! can convert anything falsey to actual boolean false, + can convert true, false, or a string representing a number into an actual number, etc.
Is there something similar that converts undefined to null?
Now I'm using ternary ? : but it would be cool to know if I'm missing a useful trick.
OK, let me contrive an example ...
function callback(value) {
return value ? format(value) : null;
}
callback is called by 3rd party code which sometimes passes undefined.
The 3rd party code can handle null being passed back, but not undefined. format() is also 3rd party and can't handle being passed either undefined or null.
Javascript now supports a null-coalescing operator:
??. It may not be production-ready (consult the support table), but it's certainly safe to use with Node or a transpiler (TypeScript, Babel, etc.).Per MDN,
Much as
||can provide a "default" value when the left operand is falsey,??provides a "default" value if the left operand is null or undefined. You can use this to coerce undefined to null:An example based on the question: