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?
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.
So, by if (fn) fn()
, you want make sure fn
is existing before executing it. the if
condition checks a Boolean value or expression, in JavaScript any falsy value could turn to a false
value in the if
Boolean checking condition. Falsy values could be:
any other value will be a truthy value.
So, if the fn
is either a null
or undefined
value, the if
checking will protect you from executing a non-function object.
By fn && fn()
, you are doing the same: in JavaScript, Boolean expression is lazy checked which means if the first part, in an &&
operation, is falsy then the second part would not be executed. So, with this feature, you could protect your code from executing a non-function object.
fn && fn()
is not an optimized version of the other one in terms of performance but is a short version in written.
Both code snippets require a precondition: the function fn
could be either not defined or an actual function object. If in your code, the fn
has the possibility of being an object of other types, such as a string, you need add type check before executing, such as:
if (fn instanceof Function) fn()
In terms of optimization, IMHO, I would say its because its a better way of making it a one line if then, without having to sacrifice braces and compromising readability, but it wouldn't make the code execute any faster