Design the Calculator State
Task
Define the information the calculator needs to remember while a calculation is in progress.
A calculator cannot rely only on what is visible on screen. It needs internal state for the current number, the previous number, and the selected operation.
Open
Open:
js/calculator.js
Before writing the calculation functions, define the initial state you will use throughout the project.
Add the state
Create a state object with these properties:
const state = {
current: '0',
previous: null,
operation: null,
waitingForOperand: false,
lastExpression: '',
justCalculated: false
};
Keep the values simple for now. Later lessons will change these properties as the user interacts with the calculator.
Why these values?
currentis the number currently being entered or displayed.previousstores the number waiting for an operation.operationstores the selected arithmetic operation.waitingForOperandtells the input logic when a new number should replace the current display.lastExpressiongives the application a place to retain the most recent expression.justCalculatedlets later input logic distinguish a new calculation from continued input.
Test
Temporarily inspect the object from the browser console or add a temporary console.log(state) after it is created.
Confirm that all six properties exist and have the expected initial values.
Checkpoint
The calculator now has an explicit state model instead of relying only on the DOM.