CodingNic

Understanding Calculator Logic

Design the Calculator State

Understanding Calculator Logic 20 min read

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:

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

  • current is the number currently being entered or displayed.
  • previous stores the number waiting for an operation.
  • operation stores the selected arithmetic operation.
  • waitingForOperand tells the input logic when a new number should replace the current display.
  • lastExpression gives the application a place to retain the most recent expression.
  • justCalculated lets 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.