== and triple equal
=== operators. It is important to know the difference between these two operators and also the difference between
Double equal “==”
5 == ‘5’ // true 0 == ‘ ‘ // true 0 == false // true null == undefined // true
As seen above, the
== operator is returning true for comparing an integer and a string in the first case, then 0 equals empty string true in the second case, 0 equals false in the third case and null equals undefined is also returning true which is not true in the last case. It is just checking the value but not the type, which is why all of the above comparisons return true. Similarly, the
!= operator is used to check inequality. If you use
!= in the above examples everything will return false. It can definitely lead to some nasty bugs in an application, so it's not recommended to use the
Note: If you are not sure about types you can go to the console and simply type “typeof ” and check its type. You can take a look at the image below to see what is returned in the console when you check the typeof. Make sure you use all lowercase letters when writing typeof and not the camelCase version of typeOf.
Triple equal “===”
Known as strict equality, it not only checks for equality of value but also datatype. It cares about value and types both which is why it's recommended to use strict equality for comparison, it's more precise. The above examples will return false when
=== is used :
5 === ‘5’ // false 0 === ‘ ‘ // false 0 === false // false null === undefined // false
!== operator is strict inequality. Beside these operators there are few more comparison operators we need to know. Here is the screen shot from the MDN documentation:
That's all for comparison operators. I hope it helps.
Happy Holidays everyone!