Search code examples
javascriptequalsreferenceequals

How to do real identity equality check for string in Javascript


I have seen many explanations of identity equal operator ===, but seems they are not quite accurate as what we understand of identity equality in other languages such as Java.

Seems for base types (such as number, string), === return true indicates if two variables are with the same type and value. But not necessarily the same identity (references to the same object). But for array and map, it does. Here are some examples that cause confusion for me:

s1 = 'a' + '1'
    s2 = 'a' + '1'
    s1 === s2  // true, even they actually reference two different 
objects in memory which suppose to be different identities. 
    
    
    a1 = [1,2]
    a2 = [1,2]
    a1 === a2  // false, as they reference two different objects in memory, even their values are the same.

Could somebody confirm my understanding is right? Also is there a real identity equality check for strings in Javascript. i.e. s1 === s2 should return false in the above example?


Solution

  • Thanks for the answers. I think the source of the truth is the Javascript language spec regarding Strict Equality Comparison. It clearly specifies the behavior in SameValueNonNumber(x, y). The confusion is many articles misused the term Identity Equality instead of Strict Equality, there's no such concept of Identity Equality based on the spec. (Although it's similar behavior for Object types as specified in item 8 in the SameValueNonNumber(x, y)). So I believe the answer is not possible to do a string identity equality check in Javascript.