0

I know the difference between == and === when applied to primitive values. But for objects, they both seem to be a simple identity comparison.

var a = {} var b = a var c = {} a == b // true a === b // true a == c // false a === c // false 

Is there any situation where comparing two objects will provide different results for each operator, or are they functionally equivalent?

5
  • There's a nice chart here: developer.mozilla.org/en-US/docs/Web/JavaScript/… the bottom, right corner describes this case. Commented Sep 7, 2018 at 19:59
  • Technically all data types are objects because they have properties and methods. What you are describing are object literals. Commented Sep 7, 2018 at 20:01
  • 1
    @marvin nope, there are primitives in js. Commented Sep 7, 2018 at 20:02
  • Here's some good reading @Marvin: developer.mozilla.org/en-US/docs/Web/JavaScript/… Commented Sep 7, 2018 at 20:03
  • 1
    @MarkMeyer and Jonas Wilms oh I guess I was mistaken. I was thinking array and strings and thats what came to my head. Thanks Mark for that, now I undestand Commented Sep 7, 2018 at 20:08

4 Answers 4

2

Yes, comparing two objects with == is the same as comparing them with ===. Just as comparing two strings with == is the same as ===. If the type of values are the same, both comparing methods will give the same result. As the specification states:

7.2.14 Abstract Equality Comparison

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. If Type(x) is the same as Type(y), then
    • Return the result of performing Strict Equality Comparison x === y.
Sign up to request clarification or add additional context in comments.

1 Comment

Looking at the specification, I hadn't considered that some objects can be converted to primitives. I think that's what I was missing in my thinking.
1

Looks like it

The only way I know to "check for object equality" in javascript is to deep check every possible key (but even then it is just duck type checking)

Comments

1

The extra = in === ensures both sides are of the same type. a and c both are objects, the same type. So == or === is irrelevant here.

Comments

-1

Well... === is "compare identity and type". You've determined that you're comparing two objects (so "type" is the same), that leaves "compare identity", which is the same as ==.

Likewise, if you compare two numbers, since you already know they are the same type (number), === is the same as ==. There is nothing special or different about objects vs. primitives here. It's just that the only type for objects is object.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.