7.3  Java Script - Functions

Index Code Tester

OBJECTIVE

DISCUSSION

Functions 

DEFINING THE FUNCTION...
function addNums(fX,fY) { 
    var fSum
    fSum = fX + fY 
    return(fSum)
    /*could replace these 3 lines with
      return(fX + fY) */
    }
DEFINING AND CALLING A FUNCTION...
function displaySum(fXX, fYY) {
    var fTotal
    fTotal = addNums(fXX, fYY)
    alert(fTotal)
    /* Could replace these 3 lines with
    alert(addNums(fXX, fYY)  */
    }
CALLING THE FUNCTION FROM HTML...

 
<div id = "myID" onclick = "alert(addNums(3,5)">Click to add 3 and 5</div>
</body>
  

EXERCISES

1.  Write a function that accepts three numbers and returns their sum.

2.  Write a function that accepts three numbers and returns their average. Use the function from #1. Create a page to test your function.  Add three textboxes and a button.  When the user clicks the button, the contents the average of the textboxes should be displayed.

3.  Write a function that accepts two strings, adds them together (with a space between them), and returns the combined string.  Create a page to test your function.

4.  Write a function that accepts two textboxes as objects and switches their values.

5.  Write a function that accepts an object and two values representing the distance in the horizontal and vertical directions. The object should be moved the amount specified.

LINKS AND HELP

http://www.jimparshall.net/javascript/javascript_functions.aspx
http://www.xs4all.nl/~ppk/js/function.html