DEV Community

Atinat Palawan
Atinat Palawan

Posted on

Not event 0 == "" but 0 == " " too.

    > 0 == ""
      True

    > 0 == " "
      True

    > 0 == "        "
      True

    > 0 == "0"
      True
Enter fullscreen mode Exit fullscreen mode

When we use == operator to do a comparison operation. There are a few cases we should be careful of, for example when we use “==” to compare 0 with “” or “ “ because all of the cases return true.

The reason is the operand on the right hand of operator == is automatically transformed to the same type as the left hand operand. In this case, the left hand operand’s type is Number so the right hand operand is transformed to the type Number as well [1].

We can see this when we try to explicitly transform these strings to type Number.

> Number("0")
  0
> Number("1")
  1
> Number("")
  0
> Number("     ")
  0
> Number("a")
  NaN
> 0 == Number("0")
  true
> 0 == Number(" ")
  True
Enter fullscreen mode Exit fullscreen mode

It looks pretty strange when Number(“”) or Number(“ “) return 0 and Number(“a”) return NaN.

As stated in mozilla.org[2] that “In most cases, using loose equality is discouraged. The result of a comparison using strict equality is easier to predict, and may evaluate more quickly due to the lack of type coercion.”. The summary of how type conversion works in Javascript when using == operator is shown in this table [3].

Ref:
[1]
https://262.ecma-international.org/5.1/#sec-11.9.3

[2]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

[3]
https://dorey.github.io/JavaScript-Equality-Table/

Top comments (0)