Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"if (fn) fn()" or "fn && fn()" [duplicate]

Tags:

javascript

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?

like image 290
Gabriel Llamas Avatar asked Mar 30 '13 16:03

Gabriel Llamas


1 Answers

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.

like image 78
T.J. Crowder Avatar answered Sep 28 '22 10:09

T.J. Crowder