DEV Community

Shrihan
Shrihan

Posted on

Type Conversion (or "Type Coercion") from one type to another in JavaScript

Simply put: Type Coercion is the process of converting from one data type to another(be it a number, string or a boolean). Coercion can be necessary for cases where you have a number in the form of a string(say, "67"), and you need to perform some numeric operations on it, for example.

In this article, we're going to look at how to convert from a data type to a number or string in JavaScript. You cannot(you can, but it's a bit clunky 😭) convert something to an array or object since they are not primitives.

String/Boolean → Number

To convert a string or Boolean to a number, there are 3 possible ways:

parseInt() and parseFloat() function

The parseInt() and parseFloat() methods are built-in to the global or window object in JavaScript. These methods take in a string and try to parse the value from the first character until the string has a valid numeral.
The parseInt function returns only the integer part, while parseFloat function returns whatever is parsed, with the decimal part.
You can also specify an optional parameter radix(only available in parseInt), which tells the function the numeral system to use while parsing. If nothing is specified, the following conditions are applicable:

  • If the string starts with "0x", then the radix parameter will default to 16(hexadecimal)
  • If the string starts with 0, then the radix parameter will default to 8(octal). This behaviour is deprecated since ES6, where it will default to 10 unless specified otherwise.
  • If the above conditions are not met, the value of the radix parameter will be 10.

If the value cannot be parsed, the function will return NaN(not a number).

Usage:

parseInt("123582jdme"); // 123582
parseInt("37.19"); // 37
parseFloat("37.19"); // 37.19
parseInt("0x8F"); // 143
parseInt("abcr2929"); // NaN
parseInt(true); // NaN
parseInt(10n); // 10
Enter fullscreen mode Exit fullscreen mode

Number constructor

The Number constructor function or "primitive object wrapper" is, again, a built-in one in JavaScript. It takes in any primitive type and converts it into a number. It can take a boolean or string(or even a number!) and tries to convert it into a numeric value. You need not use the new keyword with it, since it is a primitive type wrapper. Like parseInt and parseFloat, you can pass into it a hexadecimal number starting with "0x", and if it cannot be converted, it returns NaN
Usage:

Number("0x89FAC"); // 565164
Number("0x0F"); // 15
Number(true); // 1
Number(false); // 0
Number(null); // 0
Number("123abc"); // NaN
Number(10n); // 10
Enter fullscreen mode Exit fullscreen mode

If you notice the last line, it returns NaN if 123abc is tried to be converted. If you are using parseInt, this will be 123. This is because parseInt and parseFloat coerce a string to a number "from the first non-whitespace character until a valid numeral", while the Number function tries to convert the number in a whole.

Also, you may notice that when a boolean is passed to parseInt or parseFloat, it returns NaN, while Number returns a number, 1 or 0, depending on the boolean. This has to do with "auto-coercion". Any thing passed to parseInt or parseFloat will be coerced to a string behind the scenes, so true will be coerced to "true" and false will be coerced to "false".

The unary plus(+) operator

The unary plus operator is used before its operand. The expression will be evaluated to the numeric form of the operand(if not already a number). Again, like Number, you can have hexadecimal numbers, prefixed with "0x", and the expression will be evaluated to NaN if the operand cannot be parsed.

Usage:

+"7" // 7
+"-3" // -3
+true // 1
+false // 0
+null // 0
+"abc123" // NaN
+10n // Uncaught TypeError: Cannot convert a BigInt value to a number
Enter fullscreen mode Exit fullscreen mode

Here, you may notice that when we try to convert a BigInt value to a number using the unary plus, it throws an exception, while the other two methods stated above convert it to regular numbers.

If you don't know what a BigInt is, check out the MDN docs.

My fav: Unary plus(+)

Browser support

You can check that out from the caniuse reports:


Number/Boolean/Array → String

To convert a boolean, number or an array to a string, there are two possible ways:

String constructor

Like Number, String is a primitive object wrapper built-in to JavaScript. It coerces whatever is passed into it, to a string. This is a super straightforward one and doesn't have any sort of weird effects.

Usage:

String(true); // "true"
String(false); // "false"
String(0x0F); // "15"
String(27); // "27"
String(undefined); // "undefined"
String(null); // "null"
String(12948975894798759879867587646); // "1.294897589479876e+28"
String(12948975894798759879867587646n); // "12948975894798759879867587646"
String([1,2,3,true]); // "1,2,3,true"
String({a: 1, b: 2, c: 3}); // '[object Object]'
Enter fullscreen mode Exit fullscreen mode

.toString() function

The toString() method is a property in all data types: number, string(!), boolean, array and object and even things like Date, Error, etc. This method, when used, yields the same result as the String primitive object wrapper, except that the undefined and null do not contain any .toString method(will error out), as they are... undefined and null 😉

Usage:

true.toString(); // "true"
false.toString(); // "false"
(0x0F).toString(); // "15"
(27).toString(); // "27"
(12948975894798759879867587646).toString(); // "1.294897589479876e+28"
(12948975894798759879867587646n).toString(); // "12948975894798759879867587646"
[1,2,3,true].toString(); // "1,2,3,true"
({a: 1, b: 2, c: 3}).toString(); // '[object Object]'
Enter fullscreen mode Exit fullscreen mode

Conclusion

Aaaaaannnd, that's it for this one. I hope you've enjoyed this article and learnt something new.

Thank you and have a great day!

Top comments (0)