Why +true is not equal to true.valueOf?

209 views Asked by At
+true // result: 1

true.valueOf() // result: true

+true === true.valueOf() // result: false

In Javascript Type Coersion, the function called for evaluation is valueOf(). But if the function is called explicity it returns a different value.

3

There are 3 answers

0
BoltClock On BEST ANSWER

the function called for evaluation is valueOf()

Not always. valueOf() is only meaningful for non-primitive types, since it is defined to return the primitive value of the given object. true by itself is a Boolean primitive and as such calling true.valueOf() would be completely redundant.

The unary + and - sign operators always return a number by definition. Since a Boolean quite conveniently converts to a number, it only makes sense that +true returns 1.

There is no reason +true and true.valueOf() should both correspond to the same value.

4
Amit Joki On

Type Coersion in Javascript happens if == is used, which is kinda loose comparison operator.

=== is strict comparison operator which doesn't coerce the types when comparing so it remains an integer and the other one bool

+true === true.valeOf() // false
+true == true.valueOf() // true

Docs:

The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.

Why true.valueOf() doesn't returns 1

The answer is true.valueOf returns true, which is the primitive value of a Boolean object. Also the quote is from MDN

The valueOf method of Boolean returns the primitive value of a Boolean object or literal Boolean as a Boolean data type.

What does +true do:

+true is same as Number(true) and it is a well known fact that 0 is false and 1 is true in almost every language. In fact in C++ they are used as booleans.

0
Suchit kumar On

for strict comparison you should do like this:

Number(true.valueOf()) === +true