A function. For this random button, and the Pi button that follows, the author decided to go with a function. Note in the code how the display (document,calculator.text.value) is created by going to the function getRandom(), which looks like this:
The function simply returns (return) a random number (created through Math.random) to the display. It seems simple enough, but you might ask why not just follow the same format for putting it all in the onClick? I guess you could, but I would think the author set this aside as a function because the random number had nothing to do with the display. By setting it in a function he separated it from any other numbers. It's probably a good idea.
<INPUT TYPE=BUTTON VALUE=" pi " NAME="pi" onClick="document.calculator.text.value+= getPi()">
Same as above. The number for Pi is returned from a function that looks like this:
Again, could the author have simply done it inside the button itself? Yes. This, I think, is just a cleaner method of doing it. Plus, Pi has a decimal point in it and that's tough to get into a simple display. Doing this solved that problem pretty quickly.
Ah, now we get to the meat of the calculator function, the equal button. You push this one, you get the answer. How you get the answer is a matter of how the author set up the script.
Remember earlier in the script, the majority of the buttons simply set numbers or operators (+, -, /, *) into the display? You clicked on the numbers and they displayed one right after the other so that when you were done putting in all of your numbers, the equation you entered appeared there in the display.
The equals button simply says "Do it!" after you've entered in the numbers. There in the display is a math equation. Click the equal button and that equation is evaluated (eval) and the result is placed into the display. Poof! Your answer! And you thought it was hard....
There's one more button to worry about. It's the one that changes a number from negative to positive or the other way around. It's clever and it will be a Script Tip unto itself.
Next Time: Positive to Negative
Enterprise Development Update
Don't miss an article. Subscribe to our newsletter below.