&& operator in Javascript
While looking through some code (javascript), I found this piece of code:
<script>window.Bootloader && Bootloader.done(["pQ27\/"]);</script>
What I don't understand is what the &&
is doing there, the code is from Facebook and is obviously minified and/or obfuscated, but it still does the same thing.
tl;dr: What does the &&
operator do here?
Solution 1:
&&
makes sure that the Bootloader
function/object exists before calling the done
method on it. The code takes advantage of boolean short circuiting to ensure the first expression evaluates to true before executing the second. See the short-circuit evaluation wikipedia entry for a more in-depth explanation.
Solution 2:
window.Bootloader && Bootloader.done(["pQ27\/"]);
it is equivalent to:
if(window.Bootloader) {
Bootloader.done(["pQ27\/"]);
}
Solution 3:
&&
is an AND
operator, just like most everywhere else. There is really nothing fancy about it.
Most languages, JavaScript included, will stop evaluating an AND
operator if the first operand is false.
In this case, if window.Bootloader
does not exist, it will be undef, which evaluates to false, so JavaScript will skip the second part.
If it is true, it continues and calls Bootloader.done(...)
.
Think of it as a shortcut for if(window.Bootloader) { Bootloader.done(...) }