Create the Calculator Object
Task
Turn the calculator state into the beginning of a reusable calculator object.
The goal is to keep the application’s state and its behavior together so later lessons can add methods without scattering calculator logic across unrelated code.
Open
Open:
js/calculator.js
Replace the standalone state setup with a Calculator class.
Add the calculator class
class Calculator {
constructor() {
this.state = {
current: '0',
previous: null,
operation: null,
waitingForOperand: false,
lastExpression: '',
justCalculated: false
};
}
clear() {
this.state.current = '0';
this.state.previous = null;
this.state.operation = null;
this.state.waitingForOperand = false;
this.state.lastExpression = '';
this.state.justCalculated = false;
}
}
const calculator = new Calculator();
The constructor creates a fresh calculator state.
The clear() method gives the application one central place to reset that state. We will connect it to the visible Clear button later.
Test
Open the browser console and inspect:
calculator.state
You should see the initial state.
Then run:
calculator.state.current = '123';
calculator.clear();
calculator.state
The state should return to its initial values.
Checkpoint
You now have a calculator object with centralized state and a reset method. The next module can build number-entry behavior on this foundation.