It’s because + is two different operators and overloads based on the type to the left, while - is only a numeric operator and coerces left and right operands to numeric. But frankly if you’re still using + for math or string concatenation in 2025, you’re doing it wrong.
It’s much better to make your own function that uses bitwise operations to do addition.
functionadd(a, b) {
while (b !== 0) {
// Calculate carrylet carry = a & b;
// Sum without carry
a = a ^ b;
// Shift carry to the left
b = carry << 1;
}
return a;
}
It’s because
+
is two different operators and overloads based on the type to the left, while-
is only a numeric operator and coerces left and right operands to numeric. But frankly if you’re still using+
for math or string concatenation in 2025, you’re doing it wrong.I know nothing about javascript, what is wrong with using + for math? perhaps naively, I’d say it looks suited for the job
The correct way to do it is to load a 500mb library that has an add function in it.
Point taken but the one I use is only ~200k for the whole package, ~11k for the actual file that gets loaded
It’s much better to make your own function that uses bitwise operations to do addition.
function add(a, b) { while (b !== 0) { // Calculate carry let carry = a & b; // Sum without carry a = a ^ b; // Shift carry to the left b = carry << 1; } return a; }
(For certain definitions of better.)
The native arithmetic operators are prone to floating point rounding errors