0

Hi I am trying to check if three values in a 2d array are the same.

I wanted to do this using the following statement:board[0][i] == board[1][i] == board[2][i].

Unfortunately this gave me false as an answer, but the following statement result in true: board[0][i] == board[1][i] && board[0][i] == board[2][i]

I can't figure out why, any ideas?

lmiv
  • 315
  • 5
  • 17

1 Answers1

4

Python supports that notation, but not javascript. So this evaluates the first comparison first and then compares the true result to the board[2][i] element, which is false.

I.e. this is the same as (a == b) == c, which has no clear relationship to equality of the given values. Consider these three values that are clearly different:

a = 'x'
b = 'y'
c = false
console.log(a == b == c)

Also, note that == and != are evil and should never be used. Use === and !== instead.

TamaMcGlinn
  • 2,840
  • 23
  • 34
  • board[2][i] could be truthy. Also this is a dupe – mplungjan May 26 '20 at 12:01
  • @mplungjan in the general case yes, but he states that the separate comparison yields true, so we can conclude that is not the case here. – TamaMcGlinn May 26 '20 at 12:03
  • Ahh I see, thanks for the insight! So a fuction like this should solve the problem? `function tripleequal(a, b, c){ return (a == b && b == c && a == c); }` – lmiv May 26 '20 at 12:05
  • 1
    Can you think of an example where `a == b && b == c` but `a != c`? – Rafalon May 26 '20 at 12:10
  • I think that triple-equality is a more sensible default to use in that function. – TamaMcGlinn May 26 '20 at 12:17
  • @Rafalon that's not possible, surely? – TamaMcGlinn May 26 '20 at 12:18
  • 1
    @TamaMcGlinn [Nothing is impossible in JavaScript](https://stackoverflow.com/questions/48270127/can-a-1-a-2-a-3-ever-evaluate-to-true). ;) – Ivar May 26 '20 at 12:19
  • 2
    @TamaMcGlinn as Ivar pointed out, it is indeed possible, but highly unlikely in production code (unless one specifically wants to ruin his company). My comment was there to show that the last `&& a == c` was likely not needed – Rafalon May 26 '20 at 12:24