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 algorithm to compare two strings is simple: Compare the first character of both strings. If the first character from the first string is greater (or less) than the other string's, then the first string is greater (or less) than the second. We're done.
Strict equality using ===Strict equality compares two values for equality. Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal.
In JavaScript, strings can be compared based on their “value”, “characters case”, “length”, or “alphabetically” order: To compare strings based on their values and characters case, use the “Strict Equality Operator (===)”.
== in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing two variables, but this operator also checks datatype and compares two values. Checks the equality of two operands without considering their type. Compares equality of two operands with their types.
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:
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.
You can experience the same behavior with numbers:
new Number(5) == new Number(5) // false
And clarify your mind by:
typeof "string" // string
typeof new String("string") // object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With