A 1 minute read written by
Another surprisingly handy new feature proposal
myFunction(somePossiblyNullVariable || 'my-default-value')
Does this look familiar?
Providing a default value for when input values are undefined is a very common scenario. Many developers tend to rely on the boolean
OR-operator for this.
This doesn't work when one of the possible values in the left-hand side expression is a so-called falsy value:
'' // an empty string 0 // the number zero false
setAllowedRespawns(config.respawns || '3')
parameters.respawns is zero, the statement would resolve to the default value, '3'.
In fact, you would need a more complex construction to make zero a possible value of
setAllowedRespawns(config.respawns != null ? config.respawns : '3')
This doesn't read very well and is difficult to remember and type.
setAllowedRespawns(parameters.respawns ?? '3')
If the left-hand side of the expression evaluates to
null, the right-hand side of the expression is returned.
The big advantage over
|| is therefore that so-called "falsy" values are passed through as legal values from the left-hand side.
Woah! Can I use it?
This feature is currently in stage 1, but is of course available as a babel plugin.