3

I have a question about how chain equality works in JavaScript.

For example in python if you have: a, b = 1, 2
a == b == False //False
Because it converts to: (a == b) and (b == False) So, finally it is False.

But when I try this in js: console.log(1==2==false) // true

I got "true". I don't know why and how it is worked in js. could you please help me out?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Sara
  • 419
  • 1
  • 6
  • 14
  • any operator could be chained ... – Nina Scholz Jun 28 '21 at 08:04
  • 2
    It's almost never a good idea to chain equality or relational operators that way in JavaScript (or most other languages in my experience, but particularly JavaScript). Use `&&` or `||`. – T.J. Crowder Jun 28 '21 at 08:05
  • @T.J.Crowder yes. I think Python is one of the very few exceptions where chaining works, e.g. `10 < x < 20` is evaluated as `10 < x && x < 20`. However, as I said, Python is in the minority there. – VLAZ Jun 28 '21 at 08:14

2 Answers2

4

Reading left to right:

1==2 is false

false==false is true

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
2

in the code 1 == 2 == false

we read it as 1 == 2 == false

so basically 1 == 2 is false

and fasle == false is true

I_love_vegetables
  • 1,575
  • 5
  • 12
  • 26