2

why it is giving false ?

As double equal compare only values so it should return true OR is it comparing references (address value) ?

var a = new Number(3);
var b =new Number(3);

a == b ; // false 
a === b ; // false

As below returns true : (result as expected )

var a = new Number(3);
var b = 3;

a == b ; // true 
a === b; // false 
deceze
  • 510,633
  • 85
  • 743
  • 889

2 Answers2

1

I think this is more of a type coercion question. As such you have to understand the rules and order in which objects and non-objects are handled.

var a = new Number(3);
var b =new Number(3);

a == b ; // false 
a === b ; // false

In your case your using the new keyword causing you to wrap the values in an object. var a and var b are two new/different objects. Objects in Javascript are unique. So == and === will only be True if you are comparing the same instance of the same object. (so a reference to that object).

The reason that this works:

var a = new Number(3);
var b = 3;

a == b ; // true 
a === b; // false 

is because of the rules that govern the implicit type coercion:

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

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

So var a is first converted to a primitive value and then compared resulting in a true value.

For an in depth explanation: https://github.com/getify/You-Dont-Know-JS/blob/master/types%20&%20grammar/ch4.md

Community
  • 1
  • 1
Jordan Maduro
  • 938
  • 7
  • 11
0

When you create the numbers like that:

var a = new Number(3);
var b =new Number(3);

You are creating unique objects. If you type this into your console

typeof(a)

You will see

"object"

As the response. The same applies to the b variable. Therefore they are not equal to each other.

But when you do this:

var x = 1; var y = 2;

and check the typeof x and y you will see "number" as the response.

Here is some extra reading for you Number in Javascript

I hope it all makes sense now.

Adrian Grzywaczewski
  • 868
  • 1
  • 12
  • 25