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?

+3


source to share


2 answers


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

.

+7


source


.valueOf

returns a primitive - an empty string. false

is also primitive.



The operator +

is shorthand for converting a variable to a number. In this case, it converts the false-y values ​​to 0 - no conflict at all.

+4


source







All Articles