Pitfalls of comparison operator

    The comparison operator (==) in JavaScript is not transitive. Translating from mathematical, this means that from the fact that a == b and a == c it does not follow that b == c .

    A simple example: What's the matter? But the fact is that the variables b and c are objects (and different), and a is a primitive value (string literal). Two object variables are considered unequal if they refer to different objects. When comparing the primitive value and the object, other rules are used - everything is reduced to strings and then compared.

    var a = "строка";
    var b = new String(a);
    var c = new String(a);

    alert(a==b); // true
    alert(a==c); // true
    alert(b==c); // false




    What is this fraught with? It is fraught with very subtle mistakes. From the programmer’s point of view, the primitive value of the string type and the object created from the string by the String () constructor are practically indistinguishable, and even in many books this moment is mentioned in passing, without concrete examples.

    The situation is similar with other primitive types and corresponding objects, for example, Number.

    So be careful when comparing two variables!

    Also popular now: