returning with &&

后端 未结 3 452
心在旅途
心在旅途 2020-12-04 18:01

What does it mean to return a value with &&?

else if (document.defaultView && document.defaultView.getComputedStyle) {

    // It uses the t         


        
相关标签:
3条回答
  • 2020-12-04 18:44

    The AND && operator does the following:

    • Evaluate operands from left to right.
    • For each operand, convert it to a boolean. If the result is false, stop and return the original value of that result.
    • If all other operands have been assessed (i.e. all were truthy), return the last operand.

    As I said, each operand is convert to a boolean, if it's 0 it's falsy and every other value different than 0 (1, 56, -2, etc etc) are truthy

    In other words, AND returns the first falsy value or the last value if none were found.

    // if the first operand is truthy,
    // AND returns the second operand:
    return 1 && 0 // 0
    return 1 && 5 // 5
    
    // if the first operand is falsy,
    // AND returns it. The second operand is ignored
    return null && 5 // null
    return 0 && "no matter what"  // 0
    

    We can also pass several values in a row. See how the first falsy one is returned:

    return 1 && 2 && null && 3 // null
    

    When all values are truthy, the last value is returned:

    return 1 && 2 && 3 // 3, the last one
    

    You can learn more about the logical operator here https://javascript.info/logical-operators

    0 讨论(0)
  • 2020-12-04 18:54

    return a && b means "return a if a is falsy, return b if a is truthy".

    It is equivalent to

    if (a) return b;
    else return a;
    
    0 讨论(0)
  • 2020-12-04 18:59

    The logical AND operator, &&, works similarly. If the first object is falsy, it returns that object. If it is truthy, it returns the second object. (from https://www.nfriedly.com/techblog/2009/07/advanced-javascript-operators-and-truthy-falsy/).

    Interesting stuff!

    EDIT: So, in your case, if document.defaultView.getComputedStyle(elem, " ") does not return a meaningful ("truthy") value, that value is returned. Otherwise, it returns s.getPropertyValue(name).

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