While it's true that ==
coerces the data type for comparison to be done, your basic question of:
As of I know ==
only check the value.but new Number(3)
is a object how
it value become 3
.
has a different answer. All objects in JavaScript inherit from Object.prototype
and that object has a valueOf()
and a toString()
method. These methods are automatically used by the JavaScript runtime when the fundamental (primitive) value or string representation of that value are required. So in this case, although new Number(3)
returns an object, the valueOf()
method is implicitly being called to return the value of 3
for the rest of the expression to work with.
From the MDN link above:
JavaScript calls the valueOf
method to convert an object to a
primitive value. You rarely need to invoke the valueOf
method
yourself; JavaScript automatically invokes it when encountering an
object where a primitive value is expected.
These methods are automatically called when needed, as I said, but you can call them as well on any object:
// There will be no implicit call for .valueOf here because there is no
// context for the JS runtime to know what you want to do with the object.
// Instead, you get {}, which means Object
console.log(new Number(3)); // {}
// But, you can get the most basic value if you want:
console.log(new Number(3).valueOf()); // 3