1

why is it like this?

let number = 5
const result = number == 4 ? 'true 1' : 'false 1' || number == 3 ? 'true 2' : 'false 2'  || number == 5 ? 'true 3' : 'false 3'
console.log(result)

// return result true 2
answer true 2 why can it be like that?

  • 2
    [Operator precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) – VLAZ May 23 '20 at 17:02
  • When you use multiple operators, use brackets. It's just easier to read. You can use [astexplorer.net](https://astexplorer.net/#/gist/9f0dc780efe97c9b01570285069f41b2/121fa379930ac3999154f5ea79aee3d1e854bab8) to check the order of execution. Expand the tree on the right side panel – adiga May 23 '20 at 17:08
  • sorry, English isn't smooth I think if 'true 1' will be changed to boolean true and checked by the operator && || then the results match – Aldi Iskandar May 23 '20 at 17:22
  • @kmoser parenthesis is a [type of bracket](https://www.mathsisfun.com/algebra/brackets.html). In this context, I meant parenthesis. – adiga May 23 '20 at 21:04

1 Answers1

4

Your statement

const result = number == 4 ? 'true 1' : 'false 1' || number == 3 ? 'true 2' : 'false 2'  || number == 5 ? 'true 3' : 'false 3'

is interpreted as if it were written

const result = (number == 4) ? 'true 1' : ('false 1' || number == 3) ? 'true 2' : ('false 2 || number == 5) ? 'true 3' : 'false 3';

In particular, this part ('false 1' || number ==3) is true because 'false 1' is a non-empty string.

I am not sure what you were attempting, but note that ? : ultimately can have just one value: either the value of the first expression, or the value of the second. Thus those 'false n' strings really don't make any sense: either one of those conditional tests of number will be true, or none will be.

Pointy
  • 405,095
  • 59
  • 585
  • 614