CodingNic

Calculator Controls

Add Backspace Logic

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

javascript
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:

javascript
if (action === 'backspace') {
  calculator.backspace();
}

Test

Try:

  • 123 → Backspace → 12
  • 12 → Backspace → 1
  • 1 → Backspace → 0
  • 0 → 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.