Why is the performance inconsistent in these two expressions?
''.valueOf()// an empty string
false.valueOf()// false
but why
+'' // 0
+false // 0
I read the tutorial, the numeric conversion algorithm:
If a method exists valueOf
and returns a primitive, then return it.
Otherwise, if a method exists toString
and returns a primitive, then returns it.
Otherwise, throw an exception.
This is a conflict with a real case, if it is a rule, then I think both ''.valueOf()
and false.valueOf()
must return 0. Can someone please tell me the possible reason?
source to share
From the Object.prototype.valueOf()
MDN page :
The valueOf () method returns the primitive value of the specified object.
Since you are calling valueOf()
on primitives, it just returns those primitives.
(In JavaScript, there are 6 primitive data types : String
, Number
, Boolean
, Null
, undefined
, Symbol
(ES6))
Now, on the Unary Plus (+)
MDN page :
The unary plus operator precedes its operand and evaluates its operand, but tries to convert it to a number if it doesn't already exist.
Basically +value
equivalent to calling Number(value)
.
Both Number('')
and Number(false)
return 0
.
source to share