1. Home
  2. Computing & Technology
  3. JavaScript

Calculator Tutorial

3. Test the Javascript

clr gif
Join the Discussion

Questions? Comments?

More of this Feature

Getting Started Convert to Javascript

The third step in creating our calculator script is to test that the formula works and that we haven't made any mistakes in converting the formula into Javascript (and also to find and correct any misprints in the original copy of the formula).

The easiest way to test the script code is to surround the script with script tags and save it as an HTML document. We can then add statements at the top of the script to assign test values to the fields that will come from the calculator and document.write statements to the bottom to write out the results of the calculation.

For my Easter Calculator I saved the following as easter.htm and initially tested it by placing alert statements between the lines in the formula to output the various values and by commenting out parts of the script until I got all of the statements working correctly. I then changed the value at the top to different years to confirm that the answer that the test page displays are correct for several different input values.

<script type="text/javascript">
var year = 2005;


var a = year % 19;
var b = Math.floor(year/100);
var c = year % 100;
var d = Math.floor(b/4);
var e = b % 4;
var f = Math.floor((b+8) / 25);
var g = Math.floor((b-f+1) / 3);
var h = (19*a + b - d - g + 15) % 30;
var i = Math.floor(c/4);
var j = c % 4;
var k = (32 + 2*e + 2*i - h - j) % 7;
var m = Math.floor((a + 11*h + 22*k) / 451);
var month = Math.floor((h + k - 7*m + 114) / 31);
var day = ((h + k - 7*m +114) % 31) + 1;

document.write('Month: ' + month + ' Day: ' + day);
</script>

I actually cheated a bit in that the formula I show on this page and the previous page has already been through the testing process and has had the necessary changes made to it to correct the misprint in the original formula, the couple of errors that I made in converting the formula to Javascript and a typo that I made in one of the statements.

So now that we have a working formula the next step is to start creating the form that will appear in our page as the calculator.

1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.