Need help with basic functionality of a calculator

I’m not sure why I’m getting this undefined value. Please give me an explanation as to why this is happening.

It is a very common error in JavaScript. The problem is global scoping of var. Because index Is var, it will “survive” outside of the for loop, and by the time any one of the callback function is called, index is 10, and of course, there’s no such element so the undefined error.

You can easily fix this particular problem by simply changing it to let

for(let index = 0; index < numbers.length; index++) {

so the scope of index is local to the for loop. But you’ll not get what you want, I believe. Instead of trying to assign separate click handler to ten digit buttons, define just one click handler which is called by all digit buttons. You can determine which button was pressed by the value of

1 Like

Thank you it actually starting working after I changed the value to let. JS can be so flexible yet so finnicky at the same time. For the second part of your response I was wondering if you could go into more detail about you mean when you say define “just one click handler which is called by all the buttons” how would that work exactly?

All the digits 1 - 9 (0 most likely needs a different handler) need the same functionality so you can define just one handler. You can set to call this handler in the html like

 <button type="button" value="7" id="seven" onclick="enterDigit('7')">7</button>
<button type="button" value="8" id="eight" onclick="enterDigit('8')">8</button>
 <button type="button" value="9" id="nine" onclick="enterDigit('9')">9</button>

I pass the digit value in the call to enterDigit(). This handler will handle the logic of appending an entered digit to the current display or start a new display (if the current display is 0).

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.