# JavaScript Calculator Help: Subtraction Not Working

I’m working on the Calculator project, but I’m running into an issue where subtraction isn’t working in some cases. For something simple, like 5 -2, I get the expected result. For something a little bit more complicated, like the case the test runner uses, it fails (in that instance, returning 33 - 0.5 instead of 32.5). Here’s the relevant code:

``````calculateTotal = () => {
const displayElements = this.state.display.split(' ');

// Checking for multiple consecutive operators isn't working
// yet, but it's not what I'm concerned about here
displayElements.forEach((element, index) => {
if (
this.operators.includes(element) &&
this.operators.slice(0, 4).includes(displayElements[index + 1])
) {
displayElements.splice(index, 1);
}
})

displayElements.forEach((element, index) => {
if (element === '*' || element === '/') {
const firstNumber = displayElements[index - 1];
const secondNumber = displayElements[index + 1];
if (element === '*') {
let result = firstNumber * secondNumber;
displayElements.splice(index - 1, 3, result);
}

if (element === '/') {
let result = firstNumber / secondNumber;
displayElements.splice(index - 1, 3, result);
}
}
});

displayElements.forEach((element, index) => {
if (element === '+' || element === '-') {
const firstNumber = displayElements[index - 1];
const secondNumber = displayElements[index + 1];
if (element === '+') {
let result = +firstNumber + +secondNumber;
console.log(result);
displayElements.splice(index - 1, 3, result);
}

if (element === '-') {
let result = firstNumber - secondNumber;
displayElements.splice(index - 1, 3, result);
}
}
});

this.setState({ display: displayElements });
};
``````

Multiplication, Division, and Addition all work as expected, and return the expected value if I log the `result` var after the operation, but it never logs it with subtraction, even in the simpler cases that work that I mentioned earlier. I’ve tried wrapping the values in Number, parseFloat, etc all to no avail. If someone can point out what I’m overlooking here, I’d appreciate it!

check this line first

The plus signs in that expresssion typecast the strings into numbers, it’s not the issue.

I noticed my error after stepping away from this project for a bit: the loops only ran once each, causing them to be incomplete. Working code looked something like this:

``````  while (displayElements.includes('+') || displayElements.includes('-')) {
displayElements.forEach((element, index) => {
const firstNumber = displayElements[index - 1];
const secondNumber = displayElements[index + 1];

if (element === '+') {
let result = +firstNumber + +secondNumber;
displayElements.splice(index - 1, 3, result);
console.log(displayElements);
}

if (element === '-') {
let result = firstNumber - secondNumber;
displayElements.splice(index - 1, 3, result);
console.log(displayElements);
}
});
}
``````