I have this code:
const my_transactions = [{amount: -100,currency: 'EUR'},{amount: -200,currency: 'EUR'},{amount: -400,currency: 'EUR'}];
let total = 0;
my_transactions.forEach(el => total = total - el.amount);
console.log('total:',total);
All the amounts are negative. I need to sum all the amounts and print out the balance.
As you can see, the balance is negative. It should print
-700
But the variable "total" gets a positive value. Why?
3
Answers
Because subtracting a negative value is the same as adding a positive value.
These produce the same result:
If your intent is for all of these negative numbers to add up to
-700
then add them instead of subtracting them:This is a sum, not substractions
For shorter code:
Simply change the minus (
-
) operator to the plus (+
).Subtracting a negative number is the same as adding a positive number.
A better approach is to reduce: