There are plenty of tutorials for == and === so please don’t guide me to a basic tutorial, my question is a bit more specific:
For example http://www.w3schools.com/jsref/jsref_obj_string.asp states that:
Syntax:
var txt = new String("string");
// or more simply:
var txt = "string";
Good, but what about this?
alert(new String("a") == new String("a")); // false
alert("a" == "a"); // true
var a = new String("a");
var b = new String("a");
alert(a == b); // false
var c = "a";
var d = "a";
alert(c == d); // true
alert(c === d); // true
alert (a === c); // false
Of course nobody calls new String() anyway, but is it something about the equality failing because new String() is handled as an object not as a string?
And of course W3Schools is not the most trusted source but I would have expected all of the above alerts to say true.
Please explain.
The “surprising results” come from the way Javascript handles equality for Objects, plus the confusion that arises between string literals and String objects. From the Mozilla reference guide for the
==operator:You can experience the same behavior with numbers:
And clarify your mind by: