Your files never leave your device
Advertisement

Build a Calculator

Building a calculator teaches you how to maintain "state" (current numbers, selected operator) and respond to multiple buttons.

Handling State

You need variables to keep track of the first number, the operator, and the second number being built.

let display = '0';
let pendingOp = null;
let firstOperand = null;

function handleNumber(numStr) {
  if (display === '0') display = numStr;
  else display += numStr;
  updateDisplay();
}

function handleOperator(op) {
  firstOperand = parseFloat(display);
  pendingOp = op;
  display = '0';
}
          

Practice

Challenge 1: Implement an equals() function that looks at firstOperand, pendingOp, and the current display, and calculates the result.

Related Guides

Sponsored Utility
While You're Here
Sponsored Recommendations
Advertisement