Number function
> var x = new Number(5)
> x === 5
false
> Number(x) === 5
true
valueOf method
> var y = new Number(5)
> y === 5
false
> y.valueOf() === 5
true
Which is the preferred option? Are there benefits to using one over the other?
For the record, I’m dealing with this within a method on Number.prototype, where I can be sure that this is always a Number object.
I would think the
valueOfis preferred, sinceNumberconversion is meant to be used with values that are not alreadyNumberobjects, but moreover –Number(x)will callvalueOfmethod onx,so essentially, you’d add an unnecessary sugar/overhead, where
valueOfis a perfectly accepted way of receiving a primitive representation of an object (Numberin your case).As a side note:
this is not correct as there is always a possibility that someone will do something like this:
would of course provide:
as output. It’s for you to decide whether you want to defend against it.