0

Why does this return statement return the appropriate strings for each valid condition? Is there something I'm missing about the && operator? It actually returns the "just now" or "1 minute ago" string or any other string that is in the code block and I'm just wondering what the reason is.

return day_diff == 0 && ( diff < 60 && "just now" ||
                          diff < 120 && "1 minute ago" ||
                  diff < 3600 && Math.floor( diff / 60 ) +  " minutes ago" ||
                  diff < 7200 && "1 hour ago" ||
                  diff < 86400 && Math.floor( diff / 3600 ) + " hours ago" ) ||
        day_diff == 1 && "Yesterday" ||
        day_diff < 7 && day_diff + " days ago" ||
        day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
CheckRaise
  • 550
  • 2
  • 16
  • 2
    maybe you shouldn't pack all the logic inside of one return statement. would make debugging a lot easier. – basilikum Aug 06 '13 at 21:16
  • Logical operators are short-circuiting and return the operand that determines the result of the expression. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators. – Felix Kling Aug 06 '13 at 21:17

2 Answers2

1

Unlike C where the && operator returns an int, or C++ where it returns a bool, the JS version of && does not return a boolean-equivalent value, it simply returns the right-hand operand unmodified if the left hand operand is "truthy".

As pointed out in the comments, if the left hand operand is "falsy", that operand will be returned directly instead, again without conversion into any other type.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

Take a look at some documentation for the JavaScript logical AND (&&) operator. && returns its second operand if its first operand can be converted to true.

Nicholas Riley
  • 43,532
  • 6
  • 101
  • 124