# Handle number overflow in JavaScript 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:

```var max = Number.MAX_VALUE;
var x = max + 10;
console.log(max, x, max===x);
var min = Number.MIN_VALUE;
var y = min / 10;
console.log(min, y, min===y);```

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

```1.7976931348623157e+308
1.7976931348623157e+308
true```

While the second console.log prints something like:

```5e-324
false```

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:

`c = a + b;`

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

`a == c-b and b == c-a`

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

```function additionDoesOverflow(a, b) {
var c = a + b;
return a !== c-b || b !== c-a;
}```

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:

```function multiplicationDoesOverflow(a, b) {
var c = a * b;
return a !== c/b || b !== c/a;
}```

### 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.