Equality Gotchas – JavaScript

Type coercion is one of the very interesting concept to understand in JavaScript. To delve deep into the understanding of this concept let us first evaluate few conditional statements into the console of google chrome (or you can use node or any suitable method to evaluation these conditions. You will have to modify your code slightly based on the method you choose to evaluate the code from snippet if not using chrome console).

false == 0 //true
false === 0 //false
false == '' //true
false === '' //false

Well, we can clearly see though we are comparing the the same operands, if we change our logical equality operator from == to === the result varies.

Important concept here to understand is when we use == operator to compare two operands and they are not of same type, the type coercion comes into the picture as one of the operands is type-casted to  the similar type of another operand and then comparison is done. E.g. false == 0, in this statement numeric value 0 is falsy value which is type-casted to Boolean equivalent and then compared and this the reason the end result is true.

When we use === operator for comparison, no type casting takes place for any of the operands involved in comparison. They are compared as it is. This means, if we compare false === 0, in this case a boolean value false is checked for equality against numeric value value zero. In that case the conditional statement false === 0 return false as an end result.

Similar is the case with != and !==, e.g.

false != 0 //false (here type coercion takes place)
false !== 0 //true (here boolean value false is evaluated against Numeric value zero)
type coercion while using != vs !==

In short, we can say that == (or !=) is abstract equality while === (or !==) is value equality (strict comparison). In abstract equality an implicit conversion of operands takes place while in value equality no such implicit conversion of value is being carried out. Strict comparison is always an correct way to carry out comparison operation except for Numbers due to floating point precision. If you are interested in digging more, especially trying different combinations of type and == (or !=) and result of such statements, I would recommend you all to go through this page over MDN.

.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: