1

I would like to understand the weird behaviour of JavaScript identity and equality operator as given below.

var a = {};
var b = {};
a === b; //false
a == b;  //false

var c = '';
var d = '';
c === d; //true
c == d;  //true

All four variables a ,b ,c and d are objects. But when comparing them, first case yields false whereas second one true.

I studied comparison from the following source: https://msdn.microsoft.com/en-us/library/d53a7bd4(v=vs.94).aspx

According to the above article, except number and boolean everything is compared by reference instead of value. So how the first case returns false and second one true.

Swanand Pangam
  • 858
  • 1
  • 10
  • 25

2 Answers2

1

c and d in your example are strings, which are primitive types in JavaScript and compared by value.

For this reason, c == d returns true.

The article is talking about string objects created usng the new String('foo') constructor, which actually creates objects. In this case, the references are compared, returning false.

console.log(new String('foo') == new String('foo')) // false
console.log('foo' == 'foo')                         // true
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
0

A (primitive) string is a value type (like Number). As such === compares its value (equality).

Objects are reference types, and for them === compares identity.

Strings are a bit crazy, as there are both primitive strings and String objects (created with new String("foo")).


== works the same way as === except that it does type conversions to "make things equal if possible". For reference types this is the same as ===, except that it also equates primitive strings and String objects.

 "abc" == new String("abc");
 "abc" !== new String("abc");
Thilo
  • 257,207
  • 101
  • 511
  • 656