Welcome to the third part of a six-part series on building a web page calculator. In the previous part I gave you the skeletons of our two standard calculator functions. But there are fine details to these functions that we have to examine and appreciate. We start with the showNum() function.
Function Details for a Web Page Calculator - First Segment continued (Page 2 of 5 )
The next statement in our present code segment is
showNumCalledOnce = true;
Remember that we have to remove the initial zero; but on a condition. Each time you type a digit, the showNum() function is called. From the explanation given so far, you would never have more than one digit on the display, because each time the showNum() function is called, whatever is on the display would be erased. So we need to erase whatever is on the display (the zero) only once; that is the first time showNum() is called.
The above variable is a global variable; it means that the showNum() function has been called once. The variable is initially set to false, meaning the showNum() function has not been called once (not called at all) . So when the showNum() function is called the first time, the first line (first “if” statement) tests to see if this variable is false. The first time, it is false, so the display is erased. After that our code segment sets it to true. The next time the showNum() function is called, it would not erase the display. In this way, you will be able to type more than one digit, e.g. 4526.
After typing a number (e.g. 510), the next thing a user will do is press an operation button (e.g. +, -, X or /). After pressing an operation button, the display should be cleared as soon as the user starts typing the next number. As we saw in the last part of the series, there is a global variable, called toClearDisplay. The variable is associated more with the operator(ID) function than with the showNum() function that we are currently analyzing. The variable is set to true by the operator(ID) function each time an operator is clicked.
The next part of our code segment, checks to see if the toClearDisplay variable is true. If it is true, it clears the display and sets the toClearDisplay variable to false. The second “if” statement in our code above does this. In this way you can type more than one digit until you click an operator, the M+ or the Equal Sign.