I have seen two different “styles” for setting a default value default to the variable argument in JavaScript:
argument = argument || default // Version 1
argument || (argument = default) // Version 2
Are these completely equivalent? Is one faster than the other, or better in some other way?
The second one avoids any assignment whatsoever if
argumentis already truthy, so it may theoretically be a smidge faster.Really though I doubt you’d ever see a difference.
Just to break it down a bit more
Assign
argumentto itself ifargumentis already truthy, otherwise assignargumenttodefaultEvaluate the boolean condition
argument || (argument = default). Ifargumentis already truthy, the evaluation will short circuit, and nothing else will happen. Ifargumentis not truthy, the second half of the boolean condition will hit, andargumentwill be assigneddefault