Difference between  loose equality and strict equality operator JavaScript

Difference between loose equality and strict equality operator JavaScript

Loose Equality operator (==) in JavaScript

In Javascript, the ‘==’ operator is also known as the loose equality operator which is mainly used to compare two values on both sides and then return true or false. This operator checks equality only after converting both the values to a common type i.e type coercion. Type coercion means that the two values are compared only after attempting to convert them into the same type.

Example:

console.log("24" == 24) //true
console.log(true == 1) //true
console.log(24 == 24) //true
console.log("24" == "24") //true

In the above code, when we compare the number 24 with the string '24', the javascript will convert the string '24' into the number value of 24 and hence we get true. Similarly when we try to check if 'true == 1', in that case, the javascript converts 1 into a truthy value and then compares and returns the boolean true.

Strict Equality operator (===) in JavaScript

The triple equals operator checks if the two values are equal given they have the same data type. In other words, this operator returns a 'true' if and only if users place the same type of operands on both sides of the operator that contains the same value.

Example:

console.log("24" === 24) //false
console.log(true === 1) //false
console.log("24" === "24") //true
console.log(24 === 24) //true

In the above code, the string '24' and the number 24 give the result as false because number and string are different data types. In the same way, boolean true and number 1 are different data types, so produce a false result.

So in general, it is recommended to use the strict equality operator to avoid the confusion of type coercion by loose equality operator.