Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we determine reference equality for strings in Javascript?

Tags:

javascript

Is there a way in Javascript to determine whether two strings point to the same location in memory? I know that for objects, ===, ==, and Object.is can be used for this purpose (see MDN: Comparison operators and MDN: Object.is()), but when used on strings, these will compare the contents of the strings, not their references...

like image 626
Nicolas Trahan Avatar asked Oct 22 '19 20:10

Nicolas Trahan


People also ask

How do you check for strings of equality?

You can check the equality of two Strings in Java using the equals() method. This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

How do you check if a string is equal to another string in JavaScript?

To check if two strings are equal in JavaScript, use equal-to operator == and pass the two strings as operands. The equal-to operator returns a boolean value of true if the two strings are equal, or else, it returns false.

What is reference equality in JavaScript?

Referential equality: We can say two objects are referentially equal when the pointers of the two objects are the same or when the operators are the same object instance. We can check referential equality in 3 ways: === (triple equals) operator or the strict equality operator.

Can you use == to compare strings in JavaScript?

Explanation of the example: In the above example, when str1 and str2 are compared after using the toUpperCase method, the expression JAVASCRIPT == JAVASCRIPT would return true as they are the same strings after both being in upper case. Here, the equality operator (==) is used to check if both the strings are the same.


1 Answers

JavaScript provides no API for determining any information about memory. It abstracts memory management.

Whether two variables containing identical strings are implemented under the hood as points to the same memory location or not is an implementation detail that you can't control or determine.

like image 197
Quentin Avatar answered Oct 03 '22 14:10

Quentin