Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript comparison operators: Identity vs. Equality

I've been trying to understand the difference between JavaScript's comparison operators: identity and equality. From what I've read, if you check the equality of two objects using ==, JavaScript will try to figure out if they are the same type and, if not, try to get them to that same type. However, === doesn't behave in the same manner. So as an example:

var n = "1";
console.log(n==1);        // outputs true
console.log(n===1);       // outputs false

So what is the difference between these "identity" operators and the regular equality operators? What is the benefit of having both?

Are there differences in performance? I would think that the identity operator would be faster since it doesn't do conversion.

Also, how do these differ when it comes to more complex objects, like arrays? Most importantly, what do conventions say about when one should be used over the other, why?

like image 818
Hristo Avatar asked Mar 27 '11 03:03

Hristo


People also ask

Should I use == or === in JavaScript?

== 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.

Is there any difference between == and === in a comparison?

The difference between == and === is that: == converts the variable values to the same type before performing comparison. This is called type coercion. === does not do any type conversion (coercion) and returns true only if both values and types are identical for the two variables being compared.

What is identity operator in JavaScript?

The identity operator JavaScript is performing the equality evaluation. The interpreter first converts both operands to the same type. Then executes the identity comparison. The identity evaluation algorithm (IEA) === : If both operands have different types, they are not strictly equal.

Why we use == and === in JavaScript?

= is used for assigning values to a variable in JavaScript. == is used for comparison between two variables irrespective of the datatype of variable. === is used for comparision between two variables but this will check strict type, which means it will check datatype and compare two values.


3 Answers

The equality operator will attempt to make the data types the same before making the comparison. On the other hand, the identity operator requires both data types to be the same as a prerequisite.

There are quite a few other posts out there similar to this questions. See:

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ? (has a nice comparison chart)
Which equals operator (== vs ===) should be used in JavaScript comparisons?

In practice, the identity operator comes in really handy when you want to be certain that a boolean value is true or false since...

1 == true     => true
true == true  => true
1 === true    => false
true === true => true
like image 176
Michael Copeland Avatar answered Oct 23 '22 18:10

Michael Copeland


The difference is that ==, <=, >= and != will do type coercion — for example, force a string to be evaluated as a number. ===, <==, >==, and !== will not do type coercion. They will compare a string to a number, and since the string "1" is not the same as the numeric value 1, the result is false.

Reference is here:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators

like image 26
Joel Coehoorn Avatar answered Oct 23 '22 20:10

Joel Coehoorn


== is the same things as ===, except that == does type conversion

To show you what I mean here is a JavaScript function that behaves exactly like ==:

// loseEqual() behaves just like `==`
function loseEqual(x, y) {
    // notice the function only uses "strict" operators 
    // like `===` and `!==` to do comparisons

    if(typeof y === typeof x) return y === x;

    if(typeof y === "function" || typeof x === "function") return false;

    // treat null and undefined the same
    var xIsNothing = (y === undefined) || (y === null);
    var yIsNothing = (x === undefined) || (x === null);

    if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);

    if(typeof x === "object") x = toPrimitive(x);
    if(typeof y === "object") y = toPrimitive(y);

    if(typeof y === typeof x) return y === x;

    // convert x and y into numbers if they are not already use the "+" trick
    if(typeof x !== "number") x = +x;
    if(typeof y !== "number") y = +y;

    return x === y;
}

function toPrimitive(obj) {
    var value = obj.valueOf();
    if(obj !== value) return value;
    return obj.toString();
}

This function should help explain why people keep saying you shouldn't use ==.

As you can see == has a lot of complicated logic for type conversion. Because of that it's hard to predict what result you are going to get - and that can lead to bugs.

Here are some examples of some results you wouldn't expect:

Unexpected Truths

[1] == true // returns true
'0' == false // returns true
[] == false // returns true
[[]] == false // returns true
[0] == false // returns true

'\r\n\t' == 0 // returns true

Unexpected Conclusions

// IF an empty string '' is equal to the number zero (0)
'' == 0 // return true

// AND the string zero '0' is equal to the number zero (0)
'0' == 0 // return true

// THEN an empty string must be equal to the string zero '0'
'' == '0' // returns **FALSE**

Objects with Special Functions

// Below are examples of objects that
// implement `valueOf()` and `toString()`

var objTest = {
    toString: function() {
        return "test";
    }
};

var obj100 = {
    valueOf: function() {
        return 100;
    }
};

var objTest100 = {
    toString: function() {
        return "test";
    },
    valueOf: function() {
        return 100;
    }
};

objTest == "test" // returns true
obj100 == 100 // returns true
objTest100 == 100 // returns true

objTest100 == "test" // returns **FALSE**
like image 11
Luis Perez Avatar answered Oct 23 '22 18:10

Luis Perez