-1

In developer.mozilla website there are some examples to show different usage of logical OR operator, but this two examples got my attention, here they are :

o8 = ''    || false      // f || f returns false
o9 = false || ''         // f || f returns ""

Why this two, return different results? I expected both of them return false.

Vahid Kamyab
  • 55
  • 1
  • 5
  • 5
    From that same page: "_If `expr1` can be converted to true, returns `expr1`; else, returns `expr2`_" – Ivar Dec 26 '21 at 14:10
  • 2
    Boolean operators use so called "short circuit" -- for OR if the first operand is "truthy", the second is not evaluated, for AND if the first operand is "falsy" the second is not evaluated. But here in the first case the first one is "falsy", so it proceeds to the second one, and returns it. In the second case it does the same – tromgy Dec 26 '21 at 14:10
  • 1
    note also that `a - b` and `b - a` may result in different values. The `||` operator imposes an order of evaluation. – Pointy Dec 26 '21 at 14:11
  • 1
    in the first example `''` is coerced to a boolean to be evaluated by the `||`, in the second it is returned as a string. – pilchard Dec 26 '21 at 14:12
  • 1
    @pilchard the `false` result in the first expression is the explicit `false` after the `||` operator, not the coerced string. – Pointy Dec 26 '21 at 14:13
  • 1
    @Pointy I didn't say it wasn't, simply that the empty string was coerced in the first and not in the second – pilchard Dec 26 '21 at 14:13
  • 1
    @pilchard you're right, I have not had enough coffee – Pointy Dec 26 '21 at 14:17
  • 1
    Despite their common names (and most common use), && and | | in most dynamically-typed languages (NOT just Javascript) are NOT "logical and" and "logical or". They simply *select* one of their two operands to return. Which one is based on the truthiness or falsiness of the two arguments. – Robin Zigmond Dec 26 '21 at 14:21

2 Answers2

1

All variables are falsy, so during each evaluation, because the first operand (left side) is coalesced to a falsy value, the operand on the right side of the || will be used.

jsejcksn
  • 27,667
  • 4
  • 38
  • 62
1

See in the same page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR

expr1 || expr2

If expr1 can be converted to true, returns expr1; else, returns expr2.

Gaël J
  • 11,274
  • 4
  • 17
  • 32