Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 10, 2022 05:56 am GMT

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:trueconsole.log(2 === "2");//Output:false/*Example 2*/console.log(true == "1");//Output:trueconsole.log(true === "1");//Output:false/*Example 3*/console.log("I am a String" == new String("I am a String."));//Output:trueconsole.log("I am a String" === new String("I am a String."));//Output:false

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. Dont forget to leave your comments below.


Original Link: https://dev.to/lawanu/what-is-difference-between-and-in-javascript-253b

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To