rTaylor
rTaylor

Reputation: 39

equals comparison operator gives bad result after used four times in a row

I have a class Square with a getter method to determine if a square is valid or not. If my square has sides of 1 my code will return true. If my square has 4 sides of 5 it returns false. Can someone explain what is happening?

As you can see I accessed this in the browser and had the following results:

enter image description here

class Square extends Polygon { 
get isValid() {
    const testArray = Object.values(this); 


    return (testArray[0] == testArray[1] == testArray[2] == testArray[3]) ? true : false

} 

Upvotes: 0

Views: 49

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

The expression

testArray[0] == testArray[1] == testArray[2] == testArray[3]

carries out == 3 times, left-to-right.

((testArray[0] == testArray[1]) == testArray[2]) == testArray[3]

The first time, when the array items are equal, the first will evaluate to true:

((testArray[0] == testArray[1]) == testArray[2]) == testArray[3]
(true == testArray[2]) == testArray[3]

If the items are numbers, the next comparison will only return true if the item is 1:

console.log(true == 1);
console.log(true == 2);
console.log(true == 5);

This is because, when using abstract equality comparison ==, when a boolean is compared to a number, the boolean is coerced to a number first, and the numeric value for true is 1.

console.log(Number(true));

The third comparison has the same trouble.

To fix it, instead take the first value (or any value), and use .every:

const oneVal = testArray[0];
return testArray.every(val => val === oneVal);

Upvotes: 2

Related Questions