17

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?

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
Zar
  • 6,786
  • 8
  • 54
  • 76

4 Answers4

22

&& 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.

Sam Dolan
  • 31,966
  • 10
  • 88
  • 84
  • 1
    There are no classes in JavaScript. Bootloader would be a function or object – calebds Jan 04 '12 at 00:35
  • 9
    It does not "make sure" *Bootloader* is either a function or an object, it just tests if the *window* object has a *Bootloader* property whose value is truthy. If so, it then assumes that it is callable. – RobG Jan 04 '12 at 02:26
19
window.Bootloader && Bootloader.done(["pQ27\/"]);

it is equivalent to:

if(window.Bootloader) {
  Bootloader.done(["pQ27\/"]);
}
Ilya Streltsyn
  • 13,076
  • 2
  • 37
  • 57
ijse
  • 2,998
  • 1
  • 19
  • 25
11

&& 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(...) }

Jeff B
  • 29,943
  • 7
  • 61
  • 90
3

also && operator returns the first encountered value of this kind: null, undefined, 0, false, NaN, ""

ex: if

var1 = 33
var2 = 0 
var3 = 45

var1 && var2 && var3
returns 0
wael
  • 366
  • 1
  • 2
  • 10