-1

I follow the below links

Why should you not use Number as a constructor? Question about object.method in JavaScript

why 3==new Number(3) gives true why ??

3== new Number(3) // true

As of I know == only check the value.but new Number(3) is a object how it value become 3.

how new Number(3) value is 3

user5711656
  • 3,310
  • 4
  • 33
  • 70

3 Answers3

3

Abstract Equality Comparison, or x == y, does, on step 10:

If Type(x) is either String, Number, BigInt, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).

So the evaluation of

3 == new Number(3)

becomes

3 == Number(new Number(3))

Although new Number(3) results in a (number) object, it then gets cast to its primitive value (a plain non-object number), and 3 == 3 is true.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

It's giving true because of coercion in javascript.

Javascript will convert object to number implicitly while evaluating equality operation.

Akshay Bande
  • 2,491
  • 2
  • 12
  • 29
1

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
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71