+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.
+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.
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
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.
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 callingtrue.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
andtrue.valueOf()
should both correspond to the same value.