[Cheat Sheet] Javascript – Equality

Note: This is part of Javascript learning roadmap.

  • the most important aspect of equality in JS is understanding the difference between strict equality comparison (=== or !==) and abstract equality comparison (== or !=) 

Strict equality (=== and !==)

  • neither value is implicitly converted – if the values have different types, the values are considered unequal
  • if the values have the same type and same value -> they are equal
  • for numbers – if they both are NaN, they are not considered equal
  • objects are compared by reference – to compare by value use _.isEqual(object, other)   from underscore.org

Abstract equality (== and !=)

  • does type coercion before comparison – tries to convert the elements to the same type 
  • 2 objects with the same value but different types will be equal when they are compared with == operator
  • it should be avoided unless type coercion is exactly the behavior we want
  • one or both sides may undergo conversions
  • after the conversion, a comparison identical to strict equality it’s made




1 == ‘1’                  but            1 !== ‘1'
1.2 == ‘1.2’              but            1.2 !== ‘1.2’ 
true == 1                 but            true !== 1 
false == 0                but            false !== 0 
false == ‘’               but            false !== ''
null == undefined         but            null !== undefined
’s’ == new String(’s’)    but           ’s’ !== new String(’s’)
NaN != NaN                and           NaN !== NaN  !!
  • x !== x only if x is NaN – this is a cool way to check if x is NaN – comparing to itself

Comparison with Object.is()

  • behaves similar to ===, with some difference on how it’s handling NaN values and 0+ and 0-
  • since it’s adding extra complexity, I never used it – but it’s good to know about it


Complete example

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 )

Google+ photo

You are commenting using your Google+ 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