Sometimes we as programmers need to compare values and then execute some code based on the comparison. There are two different operators we can use. They are “==” and “===”. Both of these operators return a boolean of true or false but there are slight differences in how they actually perform the comparison.
Equality Operator: ==
- compares values if they are equivalent
- to compare two different data types of a string and a number, the operator will convert it to one type or the other. This is also known as “type conversion”.
For example:const isEqual = (num) => {
if(num == 10) {
return true
}
return false
}isEqual(10) // returns true
isEqual('10') // returns true because of type version from string to a number
Strict Equality Operator: ===
- evaluates the values as-is
- does not perform a type conversion to the data types if they are different
For example:const isEqual = (num) => {
if(num === 11) {
return true
}
return false
}isEqual(11) // returns true
isEqual('11') // returns false because it is a string data type and does not perform type conversion
The way I like to think about it is if I want to compare the value exactly as it is, I want to be extra and throw in the third ‘=’ sign, otherwise I just compare normally with the ‘==’.
I hope this helps if anyone has been confused about how to use these operators.