== and === operator has always been the topic of online discussion. Let's see how these two are different from each other.
Double equal(==) sign check for loose equality while Triple equal (===) sign checks for strict equality. The difference is that (==)loose equality will attempt to resolve the datatype via type coercion before making it comparison while (===)strict equality will return false if the data types are different. Let me give you some examples to understand it better.
/*Example 1*/ console.log(2== "2");//Output:true console.log(2 === "2");//Output:false /*Example 2*/ console.log(true == "1");//Output:true console.log(true === "1");//Output:false /*Example 3*/ console.log("I am a String" == new String("I am a String."));//Output:true console.log("I am a String" === new String("I am a String."));//Output:false
In example 1 you can see that using two equal signs(==) returns true because the string "2" is converted to the number 2 before the comparison is made but with (===)three equal signs it sees that the types are different 2 is the number and "2" is a string and then it returns false.
This is an interesting example. In (===) strict equality we can see that it returns false. It illustrates that String Literals are different from String Object. However in (==) loose equality it convert the object to literals before comparison and then returns true.
It is better to use (===) strict equality in your code because it will increase the clarity of code and prevent any false positive.
I hope you enjoyed this article. Thank you for reading. Please share it with your network. Don’t forget to leave your comments below.