For C# developers, Javascript has always surprised by its weird behavior. In this post, we are going to talk about one of the very common topics, equality check. In C#, we all have used == or != to check the equality and most of us using/used it in JavaScript in the same way. But in JS, it doesn’t behave as per the expectations each time. Because while doing the comparison, if the type of the values are different, then it internally converts it to the same type first, like if we do 0 == “0”, it will return true although number zero and string zero are not equal. We have another option for equality check as ===. Let’s see the difference at a high level
But before moving further, lets first see the primitive types in JavaScript. It is seven in total.
- undefined ( A variable which is declared but no value got assigned to it)
- null ( This type just has one value null)
- Boolean (true/false as expected)
- Number (All the numbers like integers, floats, double, decimal. It also includes Infinity and NaN )
- BigInt (New type – use for storing number greater than 2**53 -1 (2 to power 53 – 1)
- String (text)
- Symbol (A unique and immutable value. Added in ECMA 2015)
Everything else is of object type. Now let’s come to topic and start with loose equality
== (Loose Equality):
As from the picture, == doesn’t care about the type and just checks the value. When we compare the values of different types like a string with a number or number with a boolean etc, it first makes it to the same type by converting the one type to another and then does the comparison. It is also called Type Coercion. So the return values are based on the content of a variable. Let’s see some examples
console.log("2" == 2) // true console.log ("2.04" == 2.04) // true console.log(true == 1) //true console.log("0" == false) //true
console.log(2 != "3") // true console.log(true != 1) // false
=== (Strict Equality):
As type-safety is one of the key features that we want from a programming language, we can use === for comparison in JavaScript. This checks type and value of both variables and accordingly produces the result. Lets see few examples
console.log(2 === 2) // true console.log("Hello" === "Hello") // true console.log ("2.04" === 2.04) // false console.log(true === 1) //false
Conclusion:
As discussed, we can see that although lots of places == is used for equality check and it works many times as expected, it is advisable to use === for equality checks. Although this can be achieved with == using and additional check of type of both values it doesn’t make any sense. Better to have coding guidelines to use strict equality operator.
Cheers
Brij