javascript functions p icking out a dress, corsage, limo, as many abstractions

Post on 22-Feb-2016

40 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

INFO100 and CSE100. Fluency with Information Technology. JavaScript Functions P icking out a dress, corsage, limo, as many abstractions. Katherine Deibel. Functions. A function is a set of statements separate from the main program code Performs a specific task / algorithm - PowerPoint PPT Presentation

TRANSCRIPT

JavaScript FunctionsPicking out a dress, corsage, limo, as many abstractions

Fluency with Information Technology

INFO100 and CSE100

Katherine Deibel

2012-02-10 Katherine Deibel, Fluency in Information Technology 1

Functions A function is a set of statements separate

from the main program code Performs a specific task / algorithm Called by the main program or other functions May involve parameters passed to it May return a value back to where it was called

Functions promote Code re-use Cleaner, simpler code

2012-02-10 Katherine Deibel, Fluency in Information Technology 2

Functions are the basis for most programming

languages

Declaring a Function in JSFunction declaration syntax:

function <name> ( <parameter list> ) {<definition>

} <name> is the function's identifier <parameter list> is a list of input variables

that are separated by commas <definition> is the program code

Note the brackets around the definition2012-02-10 Katherine Deibel, Fluency in Information Technology 3

Naming Variables & Functions Many different standards of practice but

share common goals Readable Memorable Consistent

My approach Start with a lowercase letter, then make each

subsequent word start with an uppercase letter Use whole words except for common shorthand:

e.g., numOf (number of) or per (percent)2012-02-10 Katherine Deibel, Fluency in Information Technology 4

A Sample Function Dinner with Friends:

Compute total with an 18% tip and return the amount everyone owes split equally

function shareOfCost( bill, numEaters ) { /* Add in an 18% tip */ return (1.18 * bill) / numEaters;}

<name>: _____________ <parameter list>: _____________ <definition>: _____________

2012-02-10 Katherine Deibel, Fluency in Information Technology 5

Declaring vs Calling a Function Declaring a function

Tells JS what the computation will do Does not tell JS to compute the function A function only runs when called

Calling a function Run the function at a specific point in the code Calling is simple: <name>(parameters);

2012-02-10 Katherine Deibel, Fluency in Information Technology 6

Calling Examples

If the function has no parameters:Math.random()

If the function has parameters:shareOfCost(91.40, 5)

2012-02-10 Katherine Deibel, Fluency in Information Technology 7

Calling a function always requires the parentheses!

function shareOfCost( bill, numEaters ) { /* Add in an 18% tip */ return (1.18 * bill) / numEaters;}

How Parameters Work When we pass on values to a function

think of them as being assigned to the assigned to the parameters as in shareOfCost(91.40, 5)

2012-02-10 Katherine Deibel, Fluency in Information Technology 8

function shareOfCost( bill, numEaters ) { /* Add in an 18% tip */ return (1.18 * bill) / numEaters;}

How Parameters Work When we pass on values to a function

think of them as being assigned to the assigned to the parameters as in shareOfCost(91.40, 5)

function shareOfCost( 91.40, 5 ) { /* Add in an 18% tip */ return (1.18 * bill) / numEaters;}

2012-02-10 Katherine Deibel, Fluency in Information Technology 9

function shareOfCost( bill, numEaters ) { /* Add in an 18% tip */ return (1.18 * bill) / numEaters;}

How Parameters Work When we pass on values to a function

think of them as being assigned to the assigned to the parameters as in shareOfCost(91.40, 5)

function shareOfCost( 91.40, 5 ) { /* Add in an 18% tip */ return (1.18 * bill) / numEaters;}

function shareOfCost( 91.40, 5 ) { /* Add in an 18% tip */ return (1.18 * 91.40) / 5;}

2012-02-10 Katherine Deibel, Fluency in Information Technology 10

function shareOfCost( bill, numEaters ) { /* Add in an 18% tip */ return (1.18 * bill) / numEaters;}

How Parameters Work When we pass on values to a function

think of them as being assigned to the assigned to the parameters as in shareOfCost(91.40, 5)

function shareOfCost( 91.40, 5 ) { /* Add in an 18% tip */ return (1.18 * bill) / numEaters;}

function shareOfCost( 91.40, 5 ) { /* Add in an 18% tip */ return (1.18 * 91.40) / 5;}

returns 21.5704

2012-02-10 Katherine Deibel, Fluency in Information Technology 11

Writing a FunctionThe experience will be worth your weight in gold

2012-02-10 Katherine Deibel, Fluency in Information Technology 12

Weight in Gold Function If someone is worth their weight in

gold, how much are they really worth Facts:

Gold sold for $1732.40 / troy oz. on Thursday, Feb 9, 2011

There are 12 troy oz. in a pound

2012-02-10 Katherine Deibel, Fluency in Information Technology 13

Katherine Deibel, Fluency in Information Technology 14

What we need We need to write the three components of

a function: <name> <parameters> <definition>

function <name> ( <parameter list> ) {

<definition>}

2012-02-10

Let's think more generally The inputs:

1732.40 dollars / troy oz The person's weight in lbs

The computation: Convert the person's weight in troy oz Multiply that by the 1732.40 worth = 1732.40 *12*weight in pounds

2012-02-10 Katherine Deibel, Fluency in Information Technology 15

Notice how we did this in one statement. We couldhave broken this up, but this is rather efficient.

Katherine Deibel, Fluency in Information Technology 16

Progress so far… We need to write the three components of a

function: <name> <parameters>

<definition>

function <name> ( <parameter list> ) {return 1732.40 * 12 * weight in pounds;

}

2012-02-10

Katherine Deibel, Fluency in Information Technology 17

But It Is Not Valid JavaScript We need to write the three components of a

function: <name> <parameters>

<definition>

function <name> ( <parameter list> ) {return 1732.40 * 12 * weight in pounds;

}

2012-02-10

weight in pounds is not a valid variable

Katherine Deibel, Fluency in Information Technology 18

Adding in the Parameters We replace weight in pounds with a

parameter variable: weightInPounds <name>

<parameters><definition>

function <name> (weightInPounds) {return 1732.40 * 12 * weightInPounds;

}

2012-02-10

Katherine Deibel, Fluency in Information Technology 19

Giving it a Name We will call the function:

worthInGold<name><parameters><definition>

function worthInGold(weightInPounds) {return 1732.40 * 12 * weightInPounds;

}

2012-02-10

Implementation Functions can be put anywhere

where scripts are For easy testing, we just embed it in

the body of a page

2012-02-10 Katherine Deibel, Fluency in Information Technology 20

<body> <script type="text/javascript"> function worthInGold(weightInPounds) { return 1732.40 * 12 * weightInPounds; } alert("An average baby is worth $"+worthInGold(7.47)+" in gold."); </script>

Try It Out (version 1)

2012-02-10 Katherine Deibel, Fluency in Information Technology 21

<body> <script type="text/javascript"> function worthInGold(weightInPounds) { return 1732.40 * 12 * weightInPounds; } alert("An average baby is worth $"+worthInGold(7.47)+" in gold."); </script>

Fixing The Cents To make the dollar format correct, we will add a

new function, roundNumber, for rounding and use it in worthInGold

roundNumber may seem complex, but returns n rounded to d decimal places

2012-02-10 Katherine Deibel, Fluency in Information Technology 22

function roundNumber(n, d) { return n.fixed(d);}

function worthInGold(weightInPounds) { return roundNumber(1732.40 * 12 * weightInPounds, 2);}

Try It Out (version 2)

2012-02-10 Katherine Deibel, Fluency in Information Technology 23

Better, but gold won't always be $1732.40 / troy oz.

Katherine Deibel, Fluency in Information Technology 24

Adding a New Parameter We remove the fixed price and edit

worthInGold to use a new parameter pricePerTroyOz

2012-02-10

function worthInGold(pricePerTroyOz, weightInPounds) { return roundNumber(pricePerTroyOz * 12 * weightInPounds, 2);}

Try It Out (version 3)

2012-02-10 Katherine Deibel, Fluency in Information Technology 25

alert("If gold is sold at $1000/oz, an average baby is worth$"

+ worthInGold(1000, 7.47) + ".");

Building An Application! Functions package computation, allowing

us to create applications easily

2012-02-10 Katherine Deibel, Fluency in Information Technology 26

The Building Process Create the basic HTML structure Add a form Add the scripts Add the event handlers

2012-02-10 Katherine Deibel, Fluency in Information Technology 27

The Form

<form><p> <input type="text" id="rateBox" size="15" onchange="" /> <label for="rateBox">Price of gold in dollars/troy ounce</label> <br/> <input type="text" id="weightBox" size="15" onchange="" /> <label for="weightBox">Your weight in pounds</label> <br/> <input type="text" id="resultBox" size="15" readonly="readonly" /> <label for="resultBox">Worth in gold!</label> <br/> <input type="button" value="Calculate" style="margin-left:-2px" onclick=""/> </p></form>

2012-02-10 Katherine Deibel, Fluency in Information Technology 28

The Form: onchange eventNotice the onchange Event HandlerIt’s like onclick, but it “applies” after user data is entered in the window

<form><p> <input type="text" id="rateBox" size="15" onchange="" /> <label for="rateBox">Price of gold in dollars/troy ounce</label> <br/> <input type="text" id="weightBox" size="15" onchange="" /> <label for="weightBox">Your weight in pounds</label> <br/> <input type="text" id="resultBox" size="15" readonly="readonly" /> <label for="resultBox">Worth in gold!</label> <br/> <input type="button" value="Calculate" style="margin-left:-2px" onclick=""/> </p></form>

Regarding the onchange Event Handler It’s like onclick, but it “applies” after

user data is entered in the window

2012-02-10 Katherine Deibel, Fluency in Information Technology 29

JavaScript First, the code in the <head></head>

<head> … <script type="text/javascript"> var goldRate=0, weightPounds=0;

function roundNumber(n, d) { return n.toFixed(d); }

function worthInGold(pricePerTroyOz, weightInPounds) { return roundNumber(pricePerTroyOz * 12 * weightInPounds, 2);

} </script></head>

2012-02-10 Katherine Deibel, Fluency in Information Technology 30

JavaScript First, the code in the <head></head>

<head> … <script type="text/javascript"> var goldRate=0, weightPounds=0;

function roundNumber(n, d) { return n.toFixed(d); }

function worthInGold(pricePerTroyOz, weightInPounds) { return roundNumber(pricePerTroyOz * 12 * weightInPounds, 2);

} </script></head>

Notice two new declared variables goldRate and weightPounds

We will use these to store the values from the two text fields

2012-02-10 Katherine Deibel, Fluency in Information Technology 31

onchange Event Handlers After the price is filled in, we save the

value from the rateBox input to the variable goldRate

onchange="goldRate = document.forms[0].rateBox.value;"

onchange="weightPounds=document.forms[0].weightBox.value;"

Similarly after the weight is filled in, we save it to the variable weightPounds

2012-02-10 Katherine Deibel, Fluency in Information Technology 32

onclick Event Handlers We want to call the worthInGold()

function and display the result in the answer window as in

onclick="document.forms[0].resultBox.value='$' + worthInGold(goldRate, weightPounds);"

2012-02-10 Katherine Deibel, Fluency in Information Technology 33

Try it out!

2012-02-10 Katherine Deibel, Fluency in Information Technology 34

Summary Functions are among the most

powerful ideas in computing We will keep using them throughout

the term, even beyond JavaScript Learning the vocabulary is helpful

because the concepts can occasionally be confusing

2012-02-10 Katherine Deibel, Fluency in Information Technology 35

top related