How to check if integer addition will overflow in JavaScript

1 Answer

0 votes
function addingWillOverflow(x, y) {
    return ((x > 0) && (y > Number.MAX_SAFE_INTEGER - x)) || 
           ((x < 0) && (y < Number.MIN_SAFE_INTEGER - x));
}

let x = 39839299, y = 1472783642;
console.log(addingWillOverflow(x, y) ? "true" : "false");

x = 9007199254740991; // Number.MAX_SAFE_INTEGER
y = 1872783642;
console.log(addingWillOverflow(x, y) ? "true" : "false");


 
 
/*
run:
 
false
true
 
*/

 



answered May 17, 2025 by avibootz

Related questions

...