Issue
This Content is from Stack Overflow. Question asked by Augusta Fidelix
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
}
Solution
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 = '';
This Question was asked in StackOverflow by Augusta Fidelix and Answered by Bergi It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.