The Full Practical Guide To Type Coercion In JavaScript: Beware Of These 3 Common Mistakes
Tags: webdev, javascript, beginners, tutorial
Published: 2023-04-24 14:09:33


>  Ever used ‘**==**’ in **JavaScript?**
Or **‘if (x)’**in **JavaScript?**
Or used **String Concatenation?**

_Hopefully, after reading this article, you can obtain some insights about the **common mistakes** to avoid in **JavaScript**!_

![The Mythical Land of JavaScript](https://cdn-images-1.medium.com/max/2048/1*MpYDyNOCUdcEWuEbo1LsTA.png)

## The 7 Primitive Types

Before I begin teaching **Type Coercion** in **JavaScript**, I would like to introduce the [**7 primitive types** in **JavaScript**.](https://262.ecma-international.org/13.0/#sec-ecmascript-language-types) And they are:

- **undefined**

- **null**

- **boolean**

- **string**

- **symbol**

- **number**

- **object** _(for those wondering what is the type of **array, arrays** are a special type of **object**)_

But for the focus of this article, we would be focusing only on the most commonly used types which are: **boolean**, **string, and number**.


## What is Type Coercion?

**Type Coercion** is the **conversion** of one type to another. There are two forms of **Type Coercion:** **Explicit** and **Implicit.**

**Explicit Coercion** is the conversion of a value from one type to another using explicit methods such as **Number(), parseInt(),** and **String().**

**Implicit Coercion** is the automatic conversion of one type to another. 
_This occurs because the operation performed on the 2 types is incompatible, and **JavaScript** has to step in to make it **compatible**._

We would be focusing on **Implicit Coercion** instead as that is where most of the **bugs** occur.

---

### String Concatenation

One common place where **Implicit Coercion** tends to occur is through **String Concatenation.**

![Behavior when a string is concatenated with different types](https://cdn-images-1.medium.com/max/2000/1*m6CptHsa4987N5j2VJowZA.png)

**JavaScript** would convert the non-string type to a **string,** and **concatenate** the string to deal with these **incompatible** types.

### Evaluation of Truthy Values

Another common use case is through the short-hand usage of **Evaluation of Truthy Values**.

![Behavior when a Non-Boolean type is being treated as a Boolean](https://cdn-images-1.medium.com/max/2000/1*CFc9GtmyHehXM-pDquFVXg.png)

These occur typically in **if statements (if (x)),** **ternary operators (x ? 1 : 0),** and basically any place in code where a **non-Boolean** variable is being treated as a **Boolean** value.

That is why it is **dangerous** to use these short-hand syntaxes if you do not know all the **edge cases** when converting a **non-Boolean** type to a **Boolean** type.

### ‘==’

Another common area where **Implicit Coercion** occurs is through the usage of ‘**==**’.

![Behavior when using ‘==’ to compare incompatible types](https://cdn-images-1.medium.com/max/2000/1*G5m7tUVlHttLgbLNlOIkFQ.png)

- For **number** and **string** comparisons, **JavaScript** will convert the **string** to a **number** using **Number()** function.

- For **boolean** and **number** comparisons, **JavaScript** will convert the **boolean** to a **number** using the **Number()** function. _**true = 1, false = 0.**_

- For **boolean** and **string** comparisons, **JavaScript** will convert the **boolean** to a **number**, then the **string** is converted to a **number**. _That is why (**false == ‘0’**) is evaluated as **true**._

## Algorithm

If you are curious, you can check out the **algorithm** for **Implicit Coercion**, [**here**](https://262.ecma-international.org/13.0/#sec-islooselyequal).

![The algorithm for IsLooselyEqual()](https://cdn-images-1.medium.com/max/2000/1*h4zQQEuZNEC4xF-foRgp3Q.png)

---

You can play with the examples above in this [**JSFiddle.**](https://jsfiddle.net/MorningLit/vb62r13o/)
{% embed https://jsfiddle.net/MorningLit/vb62r13o/ %}

## Conclusion

I hope that after reading this article you would think twice about using these **unsafe** methods. You can see how by not carefully considering all the **edge cases** of **Type Coercion**, **bugs** can easily occur.

### Consider these safer alternatives:

* Utilising ‘**===**’ instead of ‘**==**’ always

* Using [**ESLint**](https://eslint.org/docs/latest/rules/no-implicit-coercion), to throw **warnings** and **errors** when you write these code

* Using **TypeScript**, to help detect potential **run-time** errors beforehand

However, of course, there is [**one** situation you might want to consider using ‘**==**’ in **JavaScript**.](https://dev.to/morninglit/the-only-situation-to-use-in-javascript-4ipd)
{% embed https://dev.to/morninglit/the-only-situation-to-use-in-javascript-4ipd %}

## Trivia

Did you know? [Someone](https://twitter.com/aemkei) even took this **Type Coercion** concept to the extreme and made a **programming language** out of it.

Behold [**http://www.jsfuck.com/**](http://www.jsfuck.com/)

It uses only **six** different characters to write and execute code in **JavaScript.** Here is a [video explanation of the makings of the programming language.](https://www.youtube.com/watch?v=sRWE5tnaxlI)

Even though this programming language looks ridiculous, there are **two** practical uses for it. And that is [**obfuscation**](https://en.wikipedia.org/wiki/Obfuscation_(software)) and the crafting of a **malicious payload** for [**XSS**.](https://owasp.org/www-community/attacks/xss/)

---

If you felt that you have learned something new, do feel free to **follow** 🥰, drop a **react 💖** or write a **comment** ✍️!
It helps makes me create and share more valuable content for **you** to become a better **Web Developer!** 🤗