<h1>String comparison WTF!</h1>
<p>
Triple equals compares by identity. This means that the two operands must refer to the SAME object in order for the expression to return true.
</p>
<p>
Double equals actually just delegates to triple equals for the comparison, but first it does a check for type. If the two operands are of the same type, they are compared using triple equals. If they are different types then Javascript attempts to convert them both to the same type.
</p>
<p>
In the example here bar1 and bar2 are of different types (primitive string and string object) so Javascript converts them both to be a string literal and so a comparison with triple equals on these will return true.
</p>
<p>
When foo and foo2 are compared using double equals, because they are different instances of the same type, double (and hence triple equals) returns false.
</p>
<p>
This experiment seems to suggest that the string literal and the string object are different types.
I need to investigate further into this issue. My understanding is that a string literal is still an object. This being so it appears that any one string is a singleton. Again, I am not certain about this.
</p>
JavaScript
/*
String comparisons
*/
var foo = new String("foo");
var foo2 = new String("foo");
// what will this output?
console.log("foo", foo == foo2);
var bar1 = "bar";
var bar2 = new String("bar");
// what will this output?
console.log("bar", bar1 == bar2);
// Can you explain what is going on?
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.