Slippery Rock University Dr. Deborah Whitfield Go Browns!

Chapter 7: Functions and Randomness

Terms:

pragmatic design
A little of both. Planning will help get the job done in a more organized fashion. Trying out detail tasks in small programs will ensure that you can in fact accomplish the end goal.
functions as problem solvers
functions that give answers. Functions that give answers do so by returning a value. The value can be used in any JS expression. Examples of functions you have used that return a value:
var x = window.prompt("enter value", "1"); // value is text string the user enters
var y = document.getElementById("someID").value; // value is a property of some element
if ( isNaN(x) ) x = 0;  // value is true or false
predefined functions
Javascript has many pre-defined functions for us to use including Math functions such as square root and rounding numbers.

Practical Example

	var textAmt = document.getElementById("liters").value;;
	var liters = parseFloat(textAmt); // now it is a number
	var rounded = Math.round(liters*10)/10; // now its rounded to 1 decimal places

There are numerous Math functions. Some of the more frequently used are:

	Math.floor (3.7);  // return the integer below 3.7 (i.e., 3)
	Math.ceil (4.2);  // return the integer above 4.2 (i.e., 5)
	Math.round (3.7);  // round the integer 3.7 (i.e., 4)
	Math.sqrt (25);  // calculate square root
	Math.min (x, y);  // return the smallest of x and y
	Math.max (x, y);  // return the largest of x and y

Math functions can be called from within Javascript code as:
	1 + Math.sqrt(4)
	alert(Math.sqrt(4));


We can also write our own functions. Have you noticed how messy the onClick is getting? Let's get that code out of the onClick and put it elsewhere.
PRACTICE
  1. Let's create a function from our previous example of converting pounds to kilograms
  2. Next, add html and a function to convert feet to meters (1 foot = 0.3048 meters

Random Function
Timing