Here we do the coding for how the calculator actually functions when we try to do calculations.

Calculator Buttons

We start defining the distinct buttons in our calculator by creating variables with constant identifiers. We execute a query using “document query Selector” to return their matching HTML elements.

For example, ‘[data-number]’ (line 1) to select all the number buttons we previously labeled using HTML, and ’[data-operation]’ (line 2) selects our operation buttons. The same applies to the “equal”, “delete”, and “all clear” buttons as well as the previousOperand and currentOperand elements. As the number and operation buttons appear multiple times on our calculator, we must use “document query Selector All” :

const numberButtons = document.querySelectorAll('[data-number]')
const operationButtons = document.querySelectorAll('[data-operation]')
const equalsButton = document.querySelector('[data-equals]')
const deleteButton = document.querySelector('[data-delete]')
const allClearButton = document.querySelector('[data-all-clear]')
const previousOperandTextElement = document.querySelector('[data-previous-operand]')
const currentOperandTextElement = document.querySelector('[data-current-operand]')

Next, we create a class to save the output of any calculations done as we make our calculator work. We do this by adding a class Calculator onto our button variables. Inside, we have a constructor including all the inputs and functions for our calculator.

We don’t define the previousOperandTextElement and currentOperandTextElement (line 2) so that they can be given values later as we perform operations. The this.clear() function (line 5) is necessary to keep the display empty and reset our inputs:

class Calculator {
	constructor(previousOperandTextElement, currentOperandTextElement) {
	this.previousOperandTextElement = previousOperandTextElement
	this.currentOperandTextElement = currentOperandTextElement
	this.clear()
}

Calculator Functions

Now we create functions with separate purposes. These will tell the buttons what to do when we use them. We will use the following functions:

clear() {
}

delete() {
}

appendNumber(number) {
}

chooseOperation(operation) {
}

compute() {
}

updateDisplay() {
}

By creating a new calculator constant and passing everything from our constructor, we can hook up our variables so they will operate on our calculator object. We then input our previous operand and current operand text elements:

const calculator = new Calculator(previousOperandTextElement, currentOperandTextElement)

The clear() function removes all values from our display. Removing the output values sets the current and previous operands to empty strings. We then must change this.operation (line 4) to undefined:

clear() {
    this.currentOperand = ' '
    this.previousOperand = ' '
    this.operation = undefined
  }