I've seen many times that fn && fn()
is an optimization of if (fn) fn()
.
My question are: why? and, what is the generated code for both solutions?
The &&
operator in JavaScript is short-circuited, meaning that if the left-hand side is false
, the right-hand side isn't evaluated at all. That's why fn && fn()
is safe even if fn
is falsey (null
, undefined
, etc.).
The "code generated" will depend entirely on the JavaScript engine, but I'd expect it to be quite similar in both cases (the &&
and the if
).
It's not an "optimization" in the sense of running faster, but rather in the sense of being shorter to write (particularly so if, like me, you never leave {}
off if
statements). It has the downside of being slightly less clear to people who are new to the language, but it's an idiom quickly learned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With