Default function parameters are used, if the argument is undefined, while the || checks for false. In Javascript, any nullish value is treated as false.
It work better, if you use nullish coalescing operator (??), but even that fails if you provide null as an argument (which usually does not happen accidentially):
In most cases the default parameters are the better solution, but there are situations where you need to set defaults in your code. It seems, there is no shorthand for all cases:
name1=typeof(name1)!==='undefined'?name1:'Guest';if(typeof(name1)!==='undefined')name1='Guest'// ----- use a default() function --------constdefault=(val,def)=>(typeof(val)==='undefined')?def:valval=default(val,"Guest")//
Version 3 may cause trouble, as shorthand behaves differently:
Default function parameters are used, if the argument is undefined, while the
||
checks forfalse
. In Javascript, any nullish value is treated asfalse
.It work better, if you use nullish coalescing operator (??), but even that fails if you provide
null
as an argument (which usually does not happen accidentially):In most cases the default parameters are the better solution, but there are situations where you need to set defaults in your code. It seems, there is no shorthand for all cases:
Thanks! I linked a caution to this excellent explained comment.