1

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);
}
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
Taylor
  • 1,223
  • 1
  • 15
  • 30

2 Answers2

1

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
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
0

This happens due to how javascript handles numbers in boolean expressions. If the first parameter in a and (&&) statement returns 0, then the right parameters will not be evaluated and 0 will be returned.