Black lives matter
Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “JavaScript for impatient programmers”
Book, exercises, quizzes
(free to read online)
Cover of book “Deep JavaScript”
Book (50% free online)
Cover of book “Tackling TypeScript”
Book (first part free online)
Logo of newsletter “ news”
Newsletter (free)

JavaScript quirk 3: normal equality (==)

(Ad, please don’t block)

[This post is part of a series on JavaScript quirks.]

Let’s start with a simple rule: the normal equality operators == and != are so problematic that you should always use strict equality (=== and !==). Some people say that there are exceptions to this rule, I disagree [2]. Keeping this rule in mind, we can now take a look at what is strange about ==, without burdening our minds unnecessarily.

The “normal” equality operator (==) has many quirks. While it is forgiving, it does not adhere to the typical rules of truthy and falsy (see quirk 1):

    > 0 == false  // OK
    > 1 == true  // OK
    > 2 == true  // not OK

    > '' == false  // OK
    > '1' == true  // OK
    > '2' == true  // not OK
Apart from that, it lets you compare values that aren’t really comparable:
    > '' == 0
    > '\n  123  \t' == 123
The last check is true because conversion to number ignores leading and trailing whitespace in JavaScript.

If you are still interested in finding out how exactly == works, you can read up on it here: [1]. With strict equality (===), values of different types are never equal [1], which means that all of the above problems go away.


  1. Equality in JavaScript: === versus ==
  2. When is it OK to use == in JavaScript?