&& operator in Javascript

后端 未结 4 745
清歌不尽
清歌不尽 2020-11-29 06:27

While looking through some code (javascript), I found this piece of code:



        
相关标签:
4条回答
  • 2020-11-29 06:31

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

    0 讨论(0)
  • 2020-11-29 06:33

    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
    
    0 讨论(0)
  • 2020-11-29 06:36
    window.Bootloader && Bootloader.done(["pQ27\/"]);
    

    it is equivalent to:

    if(window.Bootloader) {
      Bootloader.done(["pQ27\/"]);
    }
    
    0 讨论(0)
  • 2020-11-29 06:37

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

    0 讨论(0)
提交回复
热议问题