2

Is it possible to check whether 2 JavaScript strings refer to the same object (like checking equality of 2 non-primitive objects does)?

When going through 2 object trees, I need to see if 2 objects are the same references or not. When those instances somewhere deep in those trees are strings, there seems to be no way to detect whether they are actually the same instances or just equal values. Or is there?

Object trees are constructed dynamically, so there should be no problem with string interning in this case.

5
  • Can you include javascript tried at Question? Commented Jul 11, 2016 at 16:58
  • What have you tried ? detect whether they are actually the same instances or just equal values Are you talking about references ? Commented Jul 11, 2016 at 17:02
  • Can you give us an example of what you're trying to do? I don't see why you would need to compare an object against itself. Commented Jul 11, 2016 at 17:02
  • would you like to check objects or strings? Commented Jul 11, 2016 at 17:05
  • I needed to compare trees of references. Some of these references refer to the same objects. Some of these objects are strings. I needed to detect when those strings are references to the same objects. As a solution, I ended up wrapping strings in both object trees into String objects. That way, when I had same references in both trees, I could detect that. Commented Jul 12, 2016 at 8:18

1 Answer 1

5

The short answer is no, "string" is a primitive data type and JavaScript does not offer insight on its memory location. However, you could create a string "object" instead of a primitive, like so:

var s1 = new String('hello'); // create a string object
var s2 = s1; // pass it as a reference
var s3 = new String('hello'); // create another string object w/ same value as "s1"
console.log(s1 === s2); // true
console.log(s1 === s3); // false

Just be aware that creating strings like this could have adverse affects (i.e. typeof new String('hello') === 'object'). For more information, refer to the "Distinction between string primitives and String objects" section of the Mozilla docs.

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

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.