The JS equality comparison issue
Tags: javascript, beginners, tutorial
Published: 2020-03-30 14:25:18

As a common starting point of learning programming languages, one of the first things to do is discover the basic types of that language. Using them to store information as variables or even creating more complex data types, in general, all languages share some simple data types between them

- _Numbers_: `1`, `2`, `-4`, `4.2`
- _Text_: `"John Doe"`, `"Insert your age"`
- _Lists_: [`"the list has"`, `3`, `"elements"`]
- _Boolean_: `true`/`false`

There are more basic types considered essential for storing information depending on each choice of language but for now, those types can fill all the needs to the reader.

Another common knowledge that a developer aspires to acquire in a new language is **compare things**. Compare information during the execution of the program and do things based on the result of the _comparision_ is essential software development. Those _comparisons_ can happen using the so-called `if`-statement and passing a comparison using one of the comparisons operators

```js
var name = "John"

if (name == "John") {
  console.log("Hi, I'm John!") // output => "Hi, I'm John!"
}
```

The result of one comparison always evaluates a _Boolean_ value: `true` or `false`. The actual comparison can be between anything and will always check if those values respect the _comparison operator_ rule. The `==` is called the _equality operator_ and compares if both values are equal and result in `true` if they are, and `false` if don't.

![Photo by Annie Spratt on Unsplash](https://dev-to-uploads.s3.amazonaws.com/i/hoibor5bhu33ftriprox.jpeg)
<figcaption>Photo by Annie Spratt on Unsplash</figcaption>

## What can be compared?

JavaScript is a language born with some features (or flaws 🤔). As JavaScript born to be a language to run inside the Browser and used by doing things across the page filled with text in it, one of the `==` features is

- Compare if two values are equal, not considering if they are _Numbers_ or _Text_.

This feature results in a strange behavior that confuses more than help. An example of this is the following code resulting in a valid comparison

```js
var age = "12"

if (age == 12) {
  console.log("I'm 12 years old!") // output => "I'm 12 years old!"
}
```

And will log the text `"I'm 12 years old!"`. At first sight, this is not a real problem but this can result in strange behaviors. Check the following code and guess what will be the result

```js
var age = "12"

if (age == 12) {
  age = age + 1
}
console.log(age) // output => ???
```

The result should be
1. _Number_ `13`
2. _Text_ `"13"`
3. _Text_ `"121"`

The result is the answer 3: `"121"`. Why?

The `+` operator behaves like a common **sum** for _Numbers_ and like a **concatenation** operator for _Text_, even if one of the parts is a _Number_. The following example helps to understand how that works

```js
var firstName = "John"
var lastName = "Doe"
var age = 12

var fullName = firstName + " " + lastName // => "John Doe"
var olderAge = 12 + 1 // => 13

```

## But what about the === operator?

After acknowledging this behavior with the `==` operator, JavaScript received a new 'comparison' operator: `===` or the **triple equality operator**. With this operator, it is possible to compare the value **and** if both of them are the same basic type.

This guarantees that the following code will only execute if the `age` variable is a _Number_ with the value of `12`

```js
var age = "12"

if (age === 12) {
  age = age + 1
}
console.log(age) // output => "12"
```

And the final log will print just the `"12"` value, as the `age` variable is a _Text_  and not a _Number_, even respecting that `age` variable has the `"12"` value.

There are more issues with the `==` operator that will not be covered here but as a small example of them, there is a comparison of `undefined` and `null` and what they evaluate

```js
undefined == null // => true
undefined === null // => false
```

![Photo by Kelly Sikkema on Unsplash](https://dev-to-uploads.s3.amazonaws.com/i/ljgy5yi4vcxocenf5j8q.jpeg)
<figcaption>Photo by Kelly Sikkema on Unsplash</figcaption>

## What operator should I use?

Here is the common ground: **Always use the `===` (triple equal) operator.**

It is equivalent to `==` in all other languages like `Python`, `C/C++`, `Ruby`, or `Java`. And in JS, there's always a good chance of using the `==` (double equal) operator resulting in hidden bugs that will haunt the future developers as long as the software keeps running.


Did I miss or forgot something? Is there a thing that you think it's not clear or can be better explained? Feel free to reach me at the comment section or by message and discuss it!

## References

- Cover Photo by [Charles "Duck" Unitas](https://unsplash.com/@unitasphotography?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
- [Should I use === or == equality comparison operator in JavaScript?](https://bytearcher.com/articles/equality-comparison-operator-javascript/) by Panu Pitkamaki
- [Equality table for ==](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using) at MDN