Swanand Pangam
Swanand Pangam

Reputation: 898

Object comparisons in JavaScript

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.

Upvotes: 1

Views: 76

Answers (2)

Thilo
Thilo

Reputation: 262464

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");

Upvotes: 0

TimoStaudinger
TimoStaudinger

Reputation: 42460

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

Upvotes: 1

Related Questions