Home > Software engineering >  Appending with ' =' in javascript
Appending with ' =' in javascript

Time:09-18

I am trying to build a Calculator using JavaScript and i am using an object oriented approach. In the constructor function, I have a method that is supposed to display the values of the numbers clicked on screen. In the displayNum method, i used ' =' to append the new number clicked to the already existing numbers but i keep getting 'undefined' before the first number i clicked. For example, if i click 8 and 9, i will get "undefined89". Here is my code

function Calculator(element) {
  this.numberBtns = [...element.querySelectorAll('[data-numbers]')]
  this.firstOperand = element.querySelector('.first-operand')
  this.secondOperand = element.querySelector('.second-operand')

  this.numberBtns.forEach((number) => {
    number.addEventListener('click', () => {
      this.displayNum(number.textContent);
      this.updateDisplay()


    })
  })

}

Calculator.prototype.updateDisplay = function() {
  this.secondOperand.textContent = this.currentOperand

}
Calculator.prototype.displayNum = function(number) {
  this.currentOperand  = number

}

CodePudding user response:

i keep getting 'undefined' before the first number

Well yes that's because this.currentOperand is undefined until you create the property. You'll want to initialise it as the empty string in the constructor:

this.currentOperand = '';
  • Related