DEV Community

Alok Kumar
Alok Kumar

Posted on

JavaScript Coercion

Coercion

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

For example - number to string

console.log(5 + "")  // '5'
Enter fullscreen mode Exit fullscreen mode

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

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

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

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

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

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

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

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

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

Let’s see some examples -

js coercion


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 -

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.'
Enter fullscreen mode Exit fullscreen mode

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

+ operator -

let age = 22;

console.log(age+"") // '22'
Enter fullscreen mode Exit fullscreen mode

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

- operator

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

Example -

js coercion

if(condition) -

js coercion

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 -

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

add(1); // 2

add("2"); // '22'
Enter fullscreen mode Exit fullscreen mode

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 -

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

add(1); // 2

add("2"); // 4
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)