jcjunction - 4 months ago 85

Javascript Question

Learning JavaScript and found that given the expression below, it evaluates to true when given this:

`transitive([1], 1, {toString:_=>'1'});`

I don't understand why.

it makes sense that the y and z are equal but how can the x and y be equal if the x and z are not equal?

`function transitive(x,y,z) {`

return x && x == y && y == z && x != z;

}

Answer

In JavaScript there is a concept of "truthiness" and "falsyness". Values like `1`

and `'1'`

are equal when compared with a loose comparison operator like `==`

, but are not strictly equal using a strict equality operator like `===`

.

The object is equal to `1`

because JavaScript uses type coercion to convert the object to a comparable value to a primitive. It does this by calling the `.toString()`

method of the object, which returns `'1'`

and as we learned above is truthy, as is `1`

, so they are considered equal when using `==`

.

This will probably be relevant: MDN: Equality comparisons and sameness.

It is best/common practice in JavaScript to always use `===`

and `!==`

in place of `==`

and `!=`

.