A guide to "===" and "==" operators in JavaScript.

A guide to "===" and "==" operators in JavaScript.

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

Try running the above code snippets in your local browser or JavaScript environment, and do some pondering about the variations and discrepancies that arise when utilizing "===" instead of "==" or vice versa.

What distinguishes "===" from "==" and how do they function within an expression?

Both operators perform an equality check, however, the difference lies in the manner in which they evaluate the equality. The "==" operator employs a complex set of rules, referred to as Type Coercion, to convert the values of both operands to a similar type before performing the check. This process of automatic type conversion, as determined by JavaScript's own set of rules, is what constitutes Type Coercion. It is important to note that Type Coercion may result in unexpected outcomes, hence it is advisable to use it cautiously and only when comparing operands of similar types, For example:

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

/* Javascript converts the non-boolean "1" to a boolean type using 
type coercion and then do the comparision and because "1" is a 
truthy value we get a true.*/

On the other hand, the strict comparison operator "===" performs a comparison that is not only based on the values, but also on the data types of the operands. Unlike the double-character comparison operator, the strict comparison operator does not perform any type conversions, and instead only returns true if both operands are of the same type and have the same value. For example:

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

/* As I said "===" is an strict comparison operator while using it to
compare "1" === true we get a false, because it checks values and type. */

Still, perplexed?

A real-world example will clear your doubts and make things look more sensible. If we use '==', it means that we are only checking if the weight of both objects is equal in value, but not necessarily in units. For example, if object A weighs 5 Litres and object B weighs 5 Kilograms, using '==' to compare their weight would give us a true result, even though the units are different.

If we use '===', it means that we are checking if the weight of both objects is equal in value and units. In this case, if object A weighs 5 pounds and object B weighs 5 ounces, using '===' to compare their weight would give us a false result because the units are different.

In conclusion, It's generally recommended to use "===" for most comparisons in JavaScript to ensure more accurate results.