Hidden gems in Type Coercion to Number

ProgrammingJun 2021

A hidden secret of the addition and subtraction operators is that they can be used for type coercion from a given type into a number. This is, in essence, equivalent to using Number().

Having said this, the more robust way of doing this is by using the parseInt() and parseFloat() methods.

Another curiosity is that the parseInt() method takes in a second argument called radix that, broadly speaking, specifies the base of the number in the string.

Useful, for example, when converting binary numbers to base10 numbers, as seen in the examples above.

No items found.