I have a question regarding a code snippet from the React.js tutorial. I'm a beginner in JavaScript, so please excuse me if this is a dumb question.
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
The purpose of this function is to evaluate the winner of a tic-tac-toe game. The square argument gets an array of nine values with type of null, "X" or "O".
Assuming that the first three values of the array are "X", the if-statement would resolve to "X" && "X" === "X" && "X" === "X". This would result in "X" === "X" === "X". So it should return trueand the player playing with the "X" has won.
But if I try it in JSBin for example, console.log("X" === "X" === "X") returns false. I just don't get it, because in my opinion "X" is equal to "X" is equal to "X".
Can anyone explain where my error in reasoning is?
Thank you very much!
Sebastian Beier
Assuming that the first three values of the array are "X", the if-statement would resolve to "X" && "X" === "X" && "X" === "X". This would result in "X" === "X" === "X".
No, it would result in "X" && true && true:
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c])
// ^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^
// "X" true true
The &&evaluates its left-hand operand and, if that result is falsy¹, results in that falsy value. If the left-hand operand's value is truthy, && evalutes its right-hand operand and takes that value as its result.
So "X" && true && true evalutes to true && true which evalutes to true.
In contrast, the === operator evalutes its left-hand operand, then its right-hand operand, and then its right-hand operand, and compares the result for strict equality (same type and value). It's also left-to-right associative, so "X" === "X" === "X" is ("X" === "X") === "X" which is true === "X" which is false, because true is not strictly equal to "X".
¹ "falsy" - When used in a boolean context (for instance, an if condition) a value is falsy if it coerces to false. The falsy values are 0, "", null, undefined, NaN, and of course false. All other values are truthy — they coerce to true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With