javascriptlogicready

Why does this function return 0


I am trying to figure out why this javascript function returns 0 when this.position.startOffset value is 0 but not when the value is a number other than 0.

ready: function() {
    return (this.position.startOffset
            && this.position.endOffset
            && this.position.representation.trim().length >= 0
            && this.text.id
            && this.user.id
            && this.concept);
}

Solution

  • The && chain will stop evaluating at the first non-truthy (falsy) value and return it. Since 0 is falsy it is returned when it is encountered. If no falsy value is encountered then the last value is returned:

    var a = 55 && [] && 0 && false && true;     // yeild 0 as it is the first falsy value to encounter
    
    console.log("a:", a);
    
    var b = 30 && true && [] && "haha";         // yeild "haha" as it is the last value (no falsy value encountered)
    
    console.log("b:", b);

    Falsy values are:

    1. null
    2. undefined
    3. the empty string '' or ""
    4. the number 0
    5. boolean false
    6. NaN