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);
}
3
  • Looks like it's evaluating boolean, true or false, 1 or 0... is that the intention? Commented Aug 25, 2017 at 16:37
  • In JavaScript, the logical "and" operator (&&) returns the first falsy value. 0 is falsy so it will return it. Commented Aug 25, 2017 at 16:39
  • 1
    What do you expect it to return? Commented Aug 25, 2017 at 16:51

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Nice answer! JavaScript is really weird.. Always would want to use typescript, or other constructs that don't rely on boolean operations on non-booleans.
NaN is also falsy.
@FelixKling facepalm!!! Thanks.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.