Calculator Controls
20 min read
Add Backspace Logic
Task
Allow the user to remove the last character from the current input.
Open
Open:
js/calculator.js
Add backspace() inside the Calculator class.
Add the method
backspace() {
if (this.state.waitingForOperand || this.state.justCalculated) {
return;
}
const current = this.state.current;
if (current.length <= 1 || (current.length === 2 && current.startsWith('-'))) {
this.state.current = '0';
return;
}
this.state.current = current.slice(0, -1);
}
Then connect it in js/ui.js:
if (action === 'backspace') {
calculator.backspace();
}
Test
Try:
123→ Backspace →1212→ Backspace →11→ Backspace →00→ Backspace →0
Also test a decimal value such as 12.5.
Checkpoint
Backspace now changes only the current input and safely handles the minimum value.