JavaScript Coercion
Tags: javascript, webdev, beginners, 100daysofcode
Published: 2022-01-25 14:28:14



## Coercion

Coercion or type coercion is the implicit or automatic conversion of values from one data type to another.

**For example -** number to string


```javascript
console.log(5 + "")  // '5'
```


Here we can see that 5 gets converted from a **number** to a **string**.

**_Note -_** type conversion is also similar to type coercion, the only difference is that type coercion is implicit while type conversion can be both implicit and explicit.

---

Let’s have a look at some of the abstract operations which perform type conversion -

### ToString

This abstract operation takes any value and gives us the representation of it in string form.

Let’s have a look at some of the examples -

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/08kw3hgpwfz7eauf8296.png)
 
 
As we can see above that **null**, **undefined**, **any boolean**, and **numbers** get converted into their **string form**.


Let’s have a look at some more examples related to arrays -

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2fe8qy305zqqdx47k0lr.png)
 
Here we can see that it converts an **empty array** to an **empty string** without square brackets (**[]**).

While in the case of non-empty arrays it converts the content into string form, but in the case of null or undefined the ToString operation leaves them, I mean literally ignores them as you can see in the third example.

Let’s have a look at some more examples related to objects -

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/udl23d5z72jydsvjs8ql.png)
 
Here we can see that the ToString operation on an object returns **'[object Object]'** also every object has access to the method **toString** from Object.prototype,  which returns **'[object Object]'**.

But we can easily override that by providing our own toString method, for example -

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tkekn13crwy9znprhs52.png)
 
Here we can see that we have provided our own toString method which simply returns the num property, and when it is passed to ToString abstract operation it gets stringified as in the last line.

Also, we can override it to return anything in place of '[object Object]' , for example - 

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ljg2xx1z6bgx4yl73it6.png)
 

Here it’ll return **“X”** for every value of num.
 

### ToNumber

The abstract operation ToNumber converts argument to a value of type Number.

Let’s see a few examples - 

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dycfxf2s1czgcediw492.png)

Here we can see that the ToNumber operation converts an **empty string** to **0**. And it converts various arguments to a value of type Number, also it works with hexadecimal numbers. And it converts **“.”** (decimal) to **NaN**.

Let’s have a look at more examples -

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o3t857o3uo4wgzri3yo9.png)
 
Here we can see that **false** and **true** gets converted to **0** and **1** respectively. Similarly **null** and **undefined** gets converted to **0** and **NaN** respectively. Also, any string which can’t be represented in the numeric form gets converted to **NaN**.

Let’s have a look at some more examples related to arrays & objects -

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0wmeteh1ityribffzin9.png)
 
Here we can see the first four cases get converted to **0** and when there are more than one element in the array it gets converted to **NaN**. Also, the ToNumber operation on objects returns **NaN** but as similar to ToString we can override that using the **valueOf** method as shown in the last line.

### ToBoolean

The abstract operation ToBoolean converts argument to a value of type Boolean according to the given Table :

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8d4lhn7nytc4o8iuuqrk.png)
 
Let’s see some examples -

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8bxn4go24wfl9hjclpf4.png)
 
---

## Implicit Coercion

You might be thinking that we generally don’t use coercion so why we are reading about it. But surprisingly we use it more often without even realizing we are using it. Let’s have a look at some examples - 

### Template strings -

```javascript
let name = "Alok";
let age = 22;

console.log(`My name is ${name} and I am ${age} years old.`); 

// 'My name is Alok and I am 22 years old.'
```


Here we can see that the age implicitly gets converted into a string.

### + operator -
 

```javascript
let age = 22;

console.log(age+"") // '22'
```

We all have used this trick numerous times to convert numbers to strings. And here also the age implicitly gets converted into a string.

**_Note :_** + operator only performs numeric addition when both the operands are number otherwise it performs string concatenation.

**Example -**

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h9dfgyyxh48cpsidiqq6.png)

### - operator

**-** operator tries to convert both operands to numeric form and only performs numeric subtraction.

**Example -**

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kzybz03ov7mwh71sr86j.png)
 

### if(condition) -

![js coercion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r5hg7lqbz68r83iaez1u.png) 

Here we can see that **if(){}** performs ToBoolean operation implicitly on arguments.

---

## Conclusion -
 
Thus we can see that we use coercion very often without even realizing we are using it and not understanding how it works can lead to buggy codes, for example -

```javascript
const add = (num) => {
  return num + num;
}

add(1); // 2

add("2"); // '22'
```

We write a function say **add** and everything seem fine but for some reason the argument came as a string, and due to **+** operator’s coercion property we didn’t get what we expected. But now as we know how **+ operator** works we can avoid it by various ways, one of them is - 

```javascript
const add = (num) => {
  return Number(num) + Number(num);
}

add(1); // 2

add("2"); // 4
```

To conclude we have to deal with coercion whether we like it or not, so by knowing how it works we can write less buggy and more efficient code.