DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Difference between == and === in JavaScript. Explained!
Lawanu Borthakur
Lawanu Borthakur

Posted on • Updated on

Difference between == and === in JavaScript. Explained!

== 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
Enter fullscreen mode Exit fullscreen mode

Example 1

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.

Example 2

In example 2 you can see that using two equal signs(==) returns true because in JavaScript true _ is 1 and _false is 0.So it is converted to 1 before comparison in loose equality. However in (===)strict equality it is not converted and returns false

Example 3

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.

Which one is better to use "==" or "==="?

It is better to use (===) strict equality in your code because it will increase the clarity of code and prevent any false positive.

Wrap Up!!

I hope you enjoyed this article. Thank you for reading. Please share it with your network. Don’t forget to leave your comments below.

Top comments (0)

What image format should you use in your next project? πŸ€”