JavaScript Worksheet Solutions

View the page's source to see the solutions along with comments.

Task 1

Ask the user for two numbers and output their sum.


Task 2

  1. Write a function called isEven that takes one parameter n and outputs the message to the user indicating if the number is even or odd.
  2. Call the function with the sum calculated in step one as its parameters.

You can find the function in the HEAD portion of the html page, so it can be used anywhere on the page.


Task 3

  1. Write an if/else statement that determines which is larger and which is smaller.
  2. Store the larger in a variable called large and the smaller in a variable called small.
  3. Output the value stored in large.

Task 4

Write a while loop that outputs the numbers from small up to large.


Task 5

Modify your while loop so that it multiplies all of the numbers between small and large together and outputs the result after the loop.

Just to keep it clear, I've copied task 4's solution here and will modify it.


Task 6

  1. Write a function called formatNumber that takes one parameter n.
  2. The function should contain one document.writeln that prints n in italics followed by a line break.
  3. Comment the line from part 4 that output the number and replace it with a call to the function formatNumber.

The function is in the head section. I've copied the loop from 4 here too and will modify it


Task 7

  1. Write a function called hypotenuse which calculates and returns the hypotenuse of a right triangle. (c from the Pythagorean theorem : a^2 + b^2 = c^2).
  2. Use the parameters side1 and side2.
  3. JavaScript does not have an exponent operator (^ does something else).
  4. Use the built in square root function: Math.sqrt.
  5. Return the value with a return statement. This function contains NO output statements.
  6. Call the function from your main script with the parameters small and large and output the result.

The function is defined in the HEAD and will be called here.


Challenge Task

  1. Write a JavaScript function to format an HTML table cell (<td> tags) that displays a number, and somehow varies the appearance of that number if it is odd or even (different colors, underlining, bold).
  2. Use the function you have written and loops to print a multiplication table for the numbers small to large.
  3. For this you will need to nest one while loop within another.

This combined html and JavaScript. Since everything is in a table, I will start with the table tags on the outside


Clif Presser<cpresser@gettysburg.edu>
Last modified: Tue Mar 4 13:02:49 EST 2014