Download presentation
Presentation is loading. Please wait.
1
Fluency with Information Technology
7th Edition Chapter 19 Programming Functions
2
Learning Objectives 1.1 Apply JavaScript rules for functions, declarations, return values, function calls, and local/global variable references 1.2 Write JavaScript functions with the proper structure 1.3 Build a UI that contains functions 1.4 Explain what a computer-generated random number is 1.5 Design web applications for mobile use 1.6 Apply your knowledge of functions in the context of publicly available software
3
1.1 Anatomy of a Function Functions are packages for algorithms
They have three parts: Name Parameters Definition These three parts form the function declaration
4
A Functional Example: Converting Temperatures
Go to Firefox's Scratchpad: Tools > Web Developer > Scratchpad Type in: Function convertC2F ( tempInC ) { return 9/5 * tempInC + 32; } ConvertC2F(0); Use ^L to execute the script
5
Programming Functions: Repeated Use
Notice that the function can be used to convert different temperatures Change the value inside the function's parentheses to try it Function package and name algorithms for repeated use
6
1.2 JavaScript's Standard Form for Functions
JavaScript requires a standard form for writing function declarations: function <name>( <parameter list> ) { <statement list> } In the example, the name is convertC2F, the only parameter in the list is tempInC, and the only statement is a return statement All of the punctuation is important: parentheses always follow a function name curly braces always come in pairs
7
Picking a Name name is the identifier for the function
It is common to use it to describe what the function does Try to pick a name that is meaningful In JavaScript function names follow the rules for identifiers: They begin with a letter, use any mix of letters, numbers, and underscores (_) Avoid reserved words
8
Parameters Parameters are the values that the function will compute on
They are the input to the function In order for the statements of the algorithm to refer to the input values, the inputs (parameters) are given names The <parameter list> is a list of names for the inputs, separated by commas Also follow the rules for identifiers Unlike normal variables, parameters Start with a defined value Don’t have to be declared with var Can only be used inside the function
9
The Function Definition
It's the algorithm written in a programming language. Follows the language’s general rules for program statements In the function definition, there must be a way to say what the result is JavaScript uses the statement return <expression>;
10
Making the Call For the function convertC2F(), lines 1 to 3 define the algorithm, which says how it works To make it actually happen, we must call the function To call a function is to ask the computer to run or execute the statements of the function to produce the answer We do this on line 5: We write the function name and give the input values, also known as arguments, in parentheses The computer follows the definition of the function and returns the answer
11
Definition Versus Call
A function’s declaration (definition) is different from its call (use) Functions are declared only once It is unnecessary to tell the computer more than once how the function works Functions are typically called many times The answers they give are needed many times One declaration, many calls
12
Forms and Functions Creating a webpage with forms to test the JavaScript Remember (from Chapter 18): Forms must be enclosed in <form> tags Text boxes are specified by an <input type="text" /> tag Text boxes have a name, size, and other attributes To refer to the value or contents of a text box id=tb in the first form of a page, write tb.value The main event handler of interest is onchange
13
1.3 Setting up the Form in HMTL
<form id="cool"> <p>Celsius Temperature <input type="text" id="textTempC" size="4" onchange="testTempF.value=Math.round (convertC2F(textTempC.value))"/>° C</p> <p>Fahrenheit Temperature <input type="text" id="textTempF" size="4" onchange="testTempC.value=Math.round(convertF2C(text TempF.value))"/>° C</p>
14
The Inputs/Outputs in the Form
The textTempC window is for Celsius temperatures The textTempF window shows Fahrenheit temperatures Either temperature conversion may be user- entered or generated by the computer JavaScript uses the <input /> tag for both input and output
15
Events and Function Calls
Convert C to F with an onchange event using this function call: textTempF.value = convertC2F(textTempC.value) When the input window (textTempC) is changed, use the value in that window as an argument to convertC2F() and assign the result to display as the value of the textTempF window. F to C conversion is similar
16
Figure 19.2 Putting It All Together: How Cool Is It?
The HTML/JavaScript source for the temperature conversion page.
17
Writing and Using Functions
Example: flipping electronic coins A coin flip is an unpredictable event whose two outcomes are “equally probable” A computer could generate a random number between 0 and 1, and round to the nearest whole number 0 could represent tails 1 could represent heads About half the time the outcome would be tails and the rest of the time it would be heads
18
Flipping Coins and "Random" Numbers
How can a computer do anything random? Aren’t they completely deterministic? Given a program and its input, isn’t the outcome perfectly predictable? Computers are not random in any way Computers generate pseudo-random numbers
19
1.4 Pseudo-Random Numbers
An invention of computer science in which an algorithm produces a sequence of numbers that passes the statistical tests for randomness. A sequence of pseudo-random numbers between 0 and 1 has the property that about half are closer to 0 and the others are closer to 1 The sequence of items, when rounded to the nearest whole number, behave like a coin flip The JavaScript random number generator function is Math.random()
20
Making coinFlip () Work in Scratchpad
function coinFlip( ) { return Math.round(Math.random()); } function flipOut( ) { if (coinFlip( )==0) return "Tails"; else return "Heads"; flipOut(); /* Tails */
21
More about Math.random()
Math.random() produces a result in the interval [0, 1) That interval notation says that any number (except 1) is possible Generally, multiplying by n expands to the interval [0,n) The numbers are whole numbers with a decimal fraction If we throw away the decimal fraction, we get whole numbers
22
Figure 19.3 Coin Flipping Application
The JavaScript and image for the eCoin Flipping page.
23
Trip Gas Mileage (MPG) Computation
Result should be in either kilometers per liter or or miles per gallon Conversion rates: gallons = liters * gallons/liter miles = kilometers * miles/kilometer
24
MPG Computing: Parameters and Inputs/Outputs
Two parameters: Volume (gallons or liters) Distance (miles or kilometers) Inputs: Values in English units Values in metric units Output: Miles per gallon
25
MPG Computing: HTML JavaScript, and CSS
There are many approaches to making this application Check the book, Appendix H, and the student files to review the code and check the GUI Which pieces of your code were the same? Which were different?
26
Customizing Pages Creating page content
A browser begins to create a page by reading through the HTML file As it comes across JavaScript tags it removes them and the text between the tags Then it does whatever the JavaScript tells it to do document.write() is a function that inserts the text of its arguments into the web page
27
Customizing the Coin Flip
Use document.write() to display on-the-fly the proper heads or tails image Locate two images to use Change the flipOut() function from giving "Heads" or "Tails" output to instead giving a text string with the name of the image file to display Add this script: <script>document.write('<img src=" ' + flipOut() + ' "alt="coin" width="150"/>');</script>
28
Customizing the Temperature Conversion
Suppose we want a grid of temperature conversions for a web page with a column for Celsius and a column for Fahrenheit Use document.write() to create the grid on the fly, one row at a time (here's row 1): document.write('<div style="display:table-row; background- color:#00ccff;">'); document.write('<div style="display:table-cell;">-10</div>'); document.write('<div style="display:table-cell;">' + convertC2F(-10) + '</div></div>');
29
1.5 Making a Web-Based Phone App
We will make a web-base phone app to show off our functions (including some not written yet). Our app will work on a laptop or desktop, but will be designed for something smaller Design for mobility Our Bean Counter app would be hard to use on a phone display because of the small buttons and drop-down menu
30
MyApps: Designing for the Mobility
The touch metaphor benefits from larger blocks and a more "open" organization We will use a two-dimensional grid of blocks that the user will tap Each will launch one of the other functions In the MyApps application, the other applications are "called" when the user taps the right block
31
MyApps: The 6 Applications
MyApps will launch: The MPG Converter/Calculator (Chapter 19) The Counter Assistant (Chapter 19) Use the same techniques as the Temperature Table The Coin Flip (Chapter 19) The Temperature Converter (Chapter 19) A Rock Paper Scissors game (Chapter 20) The Magic Decider (Chapter 20) Build the MyApps home page, then build (or refine) the linked applications
32
Why Use Functions? Reuse: functions can be building blocks for future programs Many are general enough to be reused Some are specific to the document Interact with specific, named controls Complexity management: keeps us organized and productive while solving problems
33
1.6 Social Functions Using other people’s code
There is a strong tradition in computing to share code From the Open Source movement, to all browsers displaying the Page Source Allows you to "boldly go" after software that you may not fully understand, but which you can still make work by trying it out and noticing what happens
34
Social Functions: An Example
Suppose you come across a page that uses the <canvas> tag from HTML5 In the draw() function, there are familiar statement forms You notice the use of rgb(200, 0, 0) and guess that it's a fill color With almost no understanding of <canvas> you’ve already tried it out You notice a function which draws a word balloon You don’t understand it deeply, but you figure the draw method probably does There is an example, so you decide to take a shot at using it
35
<canvas> Element: Word Balloon
Adding text to a word balloon Use the existing function to make the balloon If we add a <p> tag after the <canvas> text it writes the text below the balloon We apply absolute position to the paragraph element, to move it to the correct position Move the balloon around After trying window.innerWidth and window.innerHeight Revise the draw() function to have x and y as parameters Use the same parameters for the text
36
<canvas> Element: Image and Positioning
Place the image Make it the background Position the balloon Set it about 700 pixels from the left side, and 10 pixels down from the top Fill in the background of the word balloon with white
37
Figure 19.15 Adding a Word Balloon to a <canvas> Element
A planned page combining an image and a word balloon comment.
38
Summary The three parts of a function—name, parameter list, and definition—are specified in a function declaration using a standard form The function declaration specifies to the computer how the function works, so we give it only once Writing functions packages algorithms, but to get their benefit in JavaScript and HTML requires that we develop web pages - we give the inputs to the functions and get their answers displayed We can develop our understanding of functions by looking for examples in code or markup, trying them, and examining the results
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.