For all its warts, JavaScript has some novelties few other languages have. In this post I want to share about JavaScript numbers, which both acknowled

The big and Small of JavaScript numbers

submited by
Style Pass
2024-10-07 08:00:02

For all its warts, JavaScript has some novelties few other languages have. In this post I want to share about JavaScript numbers, which both acknowledge normal mathematics and the fact that they are represented by an imperfect data format.

JavaScript numbers are all internally represented by a double-precision floating-point value, which means that there are perfect and imperfect representations of whole numbers as well as normal double-type floating-point values. Additionally, this is augmented by a few special values representing infinities and impossible numbers. Numbers do not overflow in JavaScript: they become positive or negative infinity. Division-by-zero does not throw an exception: it returns infinity (the limit rule). Nonsense math does not yield nonsense answers: it returns “not a number.”

While I encourage you to read the MDN article on Number, I want to provide a few patterns I have found useful when working in JavaScript that I can’t often use in other languages. In many cases we can turn iffy code (code with conditional branching) into code that simply always works regardless of the input. Here is a list of a few of those patterns. Do you have others up your sleeve?

Leave a Comment