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.

6
  • So how the first case returns true and second one false. other way around, first is false, second is true Commented Aug 24, 2016 at 13:20
  • 3
    Strings are primitives. Welcome to the beautiful world of JS. Commented Aug 24, 2016 at 13:20
  • Possible duplicate of Is String a Primitive type or Object in Javascript? Commented Aug 24, 2016 at 13:21
  • try var c = new String(''), d = new String(''); then see how you go Commented Aug 24, 2016 at 13:21
  • The article you linked to in the question says explicitly that strings are compared by value. Commented Aug 24, 2016 at 13:22

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.