While I was solving an algorithmic problem, I came to a point where I had to work with large numbers in JavaScript. I had to be sure the result doesn’t overflow (or, if it did, I wanted to know that). In a classical man versus machine match, you will see that I handle number overflow a bit different from what Javascript itself does. If you want to be surprised by how JavaScript works with numeric overflow, just execute the following lines of code:

You will realize that the actual output is different that expected. The first console.log will print something like:

While the second console.log prints something like:

What is happening there, really? Well, in the first case, when JavaScript detects a max overflow, it will just assign Number.MAX_VALUE, while in the second case, when JavaScript detects a min overflow, it just assigns 0.

Dealing with JavaScript overflow


You may need to detect overflow for various purposes, such as data validations. The easiest way to deal with this is to check the inverse operation. See the following solutions for different operations.

Handle number overflow during addition

Lets say we have the following addition:

If the addition didn’t overflow, the following is true:

So the easiest way to check for overflow when adding two numbers is to have such a function:

From now on, when we deal with large numbers that may overflow, we just have to call this function each time before any addition.

Handle number overflow during multiplication

As you probably guessed, there is a similar approach for multiplication:

Overflow for other operations

I don’t want to fill this post with examples for all possible operations. You got the idea from the above 2 examples and you can implement it to handle any other operation.

What about big numbers?


Sometimes, just knowing if an operation overflows is not enough. There are cases when you really have to deal with big numbers that JavaScript itself can’t handle. In such circumstances, you can count (pun intended!) on a math library like mathjs. This library supports numbers, big numbers, complex numbers, fractions, units, strings, arrays and matrices. Of course, it comes with a cost from the performance point of view, both memory and speed-wise, so be cautious when you choose this option.

Here at Algotech Solutions, we enjoy coding in Javascript, both on frontend and backend, through NodeJs. If you would like to know more about the way we develop, you can check out our technology stack here and here, or read our articles on Javascript ES6, chart generation or animation.

If you enjoyed this article please take a moment and share it with your friends: