Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Functions - Introduction to Java Script - Lecture Slides, Slides of Javascript programming

Here is my collection on JavaScript lectures. It includes tutorials as well as general concepts explanations. Particularly these slides contain: Functions, Program Modules, Functions, Left Parenthesis, Function Definitions, Random-Number Generation, Game of Chance, Scope Rules, Javascript Global Functions, Recursion

Typology: Slides

2013/2014

Uploaded on 01/29/2014

surii
surii 🇮🇳

3.5

(13)

130 documents

1 / 58

Toggle sidebar

Related documents


Partial preview of the text

Download Functions - Introduction to Java Script - Lecture Slides and more Slides Javascript programming in PDF only on Docsity! JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3 Programmer-Defined Functions 10.4 Function Definitions 10.5 Random-Number Generation 10.6 Example: Game of Chance 10.7 Another Example: Random Image Generator 10.8 Scope Rules 10.9 JavaScript Global Functions 10.10 Recursion 10.11 Recursion vs. Iteration 10.12 Web Resources docsity.com Objectives • In this tutorial, you will learn: – To understand how to construct programs modularly from small pieces called functions. – To be able to create new functions. – To understand the mechanisms used to pass information between functions. – To introduce simulation techniques that use random-number generation. – To understand how the visibility of identifiers is limited to specific regions of programs. docsity.com 10.2 Program Modules in JavaScript • Functions – Started by function call – Receive necessary information via arguments (parameters) – Boss-Worker relationship • Calling function • Called function • Return value when finished • Can have many tiers docsity.com 10.2 Program Modules in JavaScript boss worker1 worker2 worker3 worker4 worker5 Fig. 10.1 Hierarchical boss-function/worker-function relationship. docsity.com 10.2 Program Modules in JavaScript • Function calls – Name – Left parenthesis – Arguments separated by commas • Constants, variables or expressions – Right parenthesis – Examples: total += parseFloat( inputValue ); total += parseFloat( s1 + s2 ); docsity.com 10.4 Function Definitions • Returning control – return statement – Can return either nothing, or a value return expression; – No return statement same as return; – Not returning a value when expected is an error docsity.com 10.4 Function Definitions • Writing a function to square two numbers – for loop from 1 to 10 – Pass each number as argument to square – return value of argument multiplied by itself – Display result docsity.com 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.2: SquareInt.html --> 6 <!-- Square function --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>A Programmer-Defined square Function</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 document.writeln( 15 "<h1>Square the numbers from 1 to 10</h1>" ); 16 17 // square the numbers from 1 to 10 18 for ( var x = 1; x <= 10; ++x ) 19 document.writeln( "The square of " + x + " is " + 20 square( x ) + "<br />" ); 21 SquareInt.html (1 of 2) Calling function square and passing it the value of x. docsity.com 10.4 Function Definitions • Finding the maximum of 3 numbers – Prompt for 3 inputs – Convert to numbers – Pass to maximum – Math.max docsity.com 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.3: maximum.html --> 6 <!-- Maximum function --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Finding the Maximum of Three Values</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var input1 = 15 window.prompt( "Enter first number", "0" ); 16 var input2 = 17 window.prompt( "Enter second number", "0" ); 18 var input3 = 19 window.prompt( "Enter third number", "0" ); 20 21 var value1 = parseFloat( input1 ); 22 var value2 = parseFloat( input2 ); 23 var value3 = parseFloat( input3 ); Maximum.html (1 of 2) Prompt for the user to input three integers. docsity.com 24 25 var maxValue = maximum( value1, value2, value3 ); 26 27 document.writeln( "First number: " + value1 + 28 "<br />Second number: " + value2 + 29 "<br />Third number: " + value3 + 30 "<br />Maximum is: " + maxValue ); 31 32 // maximum method definition (called from line 25) 33 function maximum( x, y, z ) 34 { 35 return Math.max( x, Math.max( y, z ) ); 36 } 37 // --> 38 </script> 39 40 </head> 41 <body> 42 <p>Click Refresh (or Reload) to run the script again</p> 43 </body> 44 </html> Maximum.html (2 of 2) Call function maximum and pass it the value of variables value1, value2 and value3. Variables x, y and z get the value of variables value1, value2 and value3, respectively. Method max returns the larger of the two integers passed to it. docsity.com 10.5 Random-Number Generation • Random-number generation introduces element of chance – Math.random var randomValue = Math.random(); – Floating point value between 0 and 1 – Adjust range by scaling and shifting – Math.floor • Always round down Math.floor( 1 + Math.random() * 6 ) docsity.com 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4 5 <!-- Fig. 10.4: RandomInt.html --> 6 <!-- Demonstrating the Random method --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Shifted and Scaled Random Integers</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var value; 15 16 document.writeln( 17 "<table border = \"1\" width = \"50%\">" ); 18 document.writeln( 19 "<caption>Random Numbers</caption><tr>" ); 20 RandomInt.html (1 of 2) docsity.com 21 for ( var i = 1; i <= 20; i++ ) { 22 value = Math.floor( 1 + Math.random() * 6 ); 23 document.writeln( "<td>" + value + "</td>" ); 24 25 // write end and start <tr> tags when 26 // i is a multiple of 5 and not 20 27 if ( i % 5 == 0 && i != 20 ) 28 document.writeln( "</tr><tr>" ); 29 } 30 31 document.writeln( "</tr></table>" ); 32 // --> 33 </script> 34 35 </head> 36 <body> 37 <p>Click Refresh (or Reload) to run the script again</p> 38 </body> 39 </html> RandomInt.html (2 of 2) The for loop creates 20 table cells (4 rows x 5 columns). Each cell is populated with a random number generated by method random. Method floor rounds the number generated by method random down. docsity.com RollDie.html (2 of 3) 22 switch ( face ) { 23 case 1: 24 ++frequency1; 25 break; 26 case 2: 27 ++frequency2; 28 break; 29 case 3: 30 ++frequency3; 31 break; 32 case 4: 33 ++frequency4; 34 break; 35 case 5: 36 ++frequency5; 37 break; 38 case 6: 39 ++frequency6; 40 break; 41 } 42 } 43 When the controlling expression, face, matches a case label, the respective frequency variable is incremented. docsity.com RollDie.html (3 of 3) 44 document.writeln( "<table border = \"1\"" + 45 "width = \"50%\">" ); 46 document.writeln( "<thead><th>Face</th>" + 47 "<th>Frequency<th></thead>" ); 48 document.writeln( "<tbody><tr><td>1</td><td>" + 49 frequency1 + "</td></tr>" ); 50 document.writeln( "<tr><td>2</td><td>" + frequency2 + 51 "</td></tr>" ); 52 document.writeln( "<tr><td>3</td><td>" + frequency3 + 53 "</td></tr>" ); 54 document.writeln( "<tr><td>4</td><td>" + frequency4 + 55 "</td></tr>" ); 56 document.writeln( "<tr><td>5</td><td>" + frequency5 + 57 "</td></tr>" ); 58 document.writeln( "<tr><td>6</td><td>" + frequency6 + 59 "</td></tr></tbody></table>" ); 60 // --> 61 </script> 62 63 </head> 64 <body> 65 <p>Click Refresh (or Reload) to run the script again</p> 66 </body> 67 </html> The results of rolling the die 600 times are displayed in a table. docsity.com 10.5 Random-Number Generation Fig. 10.5 Rolling a six-sided die 6000 times. docsity.com 10.6 Example: Game of Chance • Changing properties – Access with dot (.) notation – value property of text fields – status property of window docsity.com 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <!-- Fig. 10.6: Craps.html --> 6 <!-- Craps Program --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Program that Simulates the Game of Craps</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 // variables used to test the state of the game 15 var WON = 0, LOST = 1, CONTINUE_ROLLING = 2; 16 17 // other variables used in program 18 var firstRoll = true, // true if first roll 19 sumOfDice = 0, // sum of the dice 20 myPoint = 0, // point if no win/loss on first roll 21 gameStatus = CONTINUE_ROLLING; // game not over yet 22 Craps.html (1 of 5) docsity.com 23 // process one roll of the dice 24 function play() 25 { 26 if ( firstRoll ) { // first roll of the dice 27 sumOfDice = rollDice(); 28 29 switch ( sumOfDice ) { 30 case 7: case 11: // win on first roll 31 gameStatus = WON; 32 // clear point field 33 document.craps.point.value = ""; 34 break; 35 case 2: case 3: case 12: // lose on first roll 36 gameStatus = LOST; 37 // clear point field 38 document.craps.point.value = ""; 39 break; 40 default: // remember point 41 gameStatus = CONTINUE_ROLLING; 42 myPoint = sumOfDice; 43 document.craps.point.value = myPoint; 44 firstRoll = false; 45 } 46 } Craps.html (2 of 5) If the value of firstRoll is true, then function rollDice is called. If function rollDice returns a value of 7 or 11, the player wins and the break statement causes program control proceeds to the first line after the switch structure. If function rollDice returns a 2, 3 or 12, the player loses and the break statement causes control to proceed to first line after the switch structure. docsity.com Craps.html (5 of 5) 90 <body> 91 <form name = "craps" action = ""> 92 <table border = "1"> 93 <caption>Craps</caption> 94 <tr><td>Die 1</td> 95 <td><input name = "firstDie" type = "text" /> 96 </td></tr> 97 <tr><td>Die 2</td> 98 <td><input name = "secondDie" type = "text" /> 99 </td></tr> 100 <tr><td>Sum</td> 101 <td><input name = "sum" type = "text" /> 102 </td></tr> 103 <tr><td>Point</td> 104 <td><input name = "point" type = "text" /> 105 </td></tr> 106 <tr><td><input type = "button" value = "Roll Dice" 107 onclick = "play()" /></td></tr> 108 </table> 109 </form> 110 </body> 111 </html> docsity.com 10.6 Example: Game of Chance Fig. 10.6 Craps game simulation. A text XHTML GUI component A button XHTML GUI component Browser’s status bar docsity.com 10.6 Example: Game of Chance Fig. 10.6 Craps game simulation. docsity.com RandomPicture.html (1 of 1) 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 4 5 <!-- Fig. 10.7: RandomPicture.html --> 6 <!-- Randomly displays one of 7 images --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Random Image Generator</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 document.write ( "<img src = \"" + 15 Math.floor( 1 + Math.random() * 7 ) + 16 ".gif\" width = \"105\" height = \"100\" />" ); 17 // --> 18 </script> 19 20 </head> 21 22 <body> 23 <p>Click Refresh (or Reload) to run the script again</p> 24 </body> 25 </html> Inserting a random number into the image’s src property with document.write and Math.random docsity.com 10.7 Another Example: Random Image Generator Fig. 10.7 Random image generation using Math.random. docsity.com 10.8 Scope Rules • Scope – Portion of program where identifier can be referenced – Inside function is local or function scope • Identifiers exist only between opening and closing braces • Local variables hide global variables docsity.com Scoping.html (2 of 3) 26 27 document.writeln( 28 "<p>local x in start is " + x + "</p>" ); 29 } 30 31 function functionA() 32 { 33 var x = 25; // initialized each time 34 // functionA is called 35 36 document.writeln( "<p>local x in functionA is " + 37 x + " after entering functionA" ); 38 ++x; 39 document.writeln( "<br />local x in functionA is " + 40 x + " before exiting functionA" + "</p>" ); 41 } 42 Function functionA changes the value of x to 25. The value of x is incremented. docsity.com Scoping.html (3 of 3) 43 function functionB() 44 { 45 document.writeln( "<p>global variable x is " + x + 46 " on entering functionB" ); 47 x *= 10; 48 document.writeln( "<br />global variable x is " + 49 x + " on exiting functionB" + "</p>" ); 50 } 51 // --> 52 </script> 53 54 </head> 55 <body onload = "start()"></body> 56 </html> Function functionB multiplies the value of x by 10. docsity.com 10.8 Scope Rules Fig. 10.8 Scoping example. html - Microsoft Internet Explorer =/5) x] File Edit ‘View Favorites Tools Help pack ~ = ~ GD [2] | Glsearch Gigravortes Gpmedia G4| E4- Sh HR ~ [S| Address |] C:\IWSHTPS\examples|ch10\scoping. html +) @Go |Links * =| local x m start is 5 local x in functionA is 25 after entering functionA local x in functionA is 26 before exiting fanctionA Global variable x is 1 on entering function global variable xis 10 on exiting function local x in functionA is 25 after entering finctionA local x in functionA is 26 before exiting fianctionA global variable x is 10 on entering functionB global variable x is 100 on exiting functionB. local x in stark is 3 [| [ [[ imvcomputer 3 docsity.com 10.9 JavaScript Global Functions Global function Description parseFloat This function takes a string argument and attempts to convert the beginning of the string into a floating- point value. If the conversion is unsuccessful, the function returns NaN; otherwise, it returns the converted value (e.g., parseFloat( "abc123.45" ) returns NaN, and parseFloat( "123.45abc" ) returns the value 123.45). parseInt This function takes a string argument and attempts to convert the beginning of the string into an integer value. If the conversion is unsuccessful, the function returns NaN; otherwise, it returns the converted value (e.g., parseInt( "abc123" ) returns NaN, and parseInt( "123abc" ) returns the integer value 123). This function takes an optional second argument, from 2 to 36, specifying the radix (or base) of the number. Base 2 indicates that the first argument string is in binary format, base 8 indicates that the first argument string is in octal format and base 16 indicates that the first argument string is in hexadecimal format. See see Appendex E, Number Systems, for more information on binary, octal and hexadecimal numbers. unescape This function takes a string as its argument and returns a string in which all characters previously encoded with escape are decoded. Fig. 10.9 JavaScript global functions. docsity.com 10.10 Recursion • Recursive functions – Call themselves • Recursion step or recursive call • Part of return statement – Must have base case • Simplest case of problem • Returns value rather than calling itself – Each recursive call simplifies input • When simplified to base case, functions return docsity.com 10.10 Recursion • Factorials – Product of calculation n · (n - 1) · (n - 2) · … · 1 – Iterative approach: var factorial = 1; for ( var counter = number; counter >= 1; --counter ) factorial *= counter; – Note each factor is one less than previous factor • Stops at 1: base case • Perfect candidate for recursive solution docsity.com 23 // Recursive definition of function factorial 24 function factorial( number ) 25 { 26 if ( number <= 1 ) // base case 27 return 1; 28 else 29 return number * factorial( number - 1 ); 30 } 31 </script> 32 </head><body></body> 33 </html> FactorialTest.html (2 of 2) Variable number gets the value of variable i. Call to function factorial and passing it 1 less than the current value of number . docsity.com 10.10 Recursion Fig. 10.11 Factorial calculation with a recursive function. docsity.com 10.11 Recursion vs. Iteration • Iteration – Explicitly uses repetition structures to achieve result – Terminates when loop-continuation condition fails – Often faster than recursion • Recursion – Repeats through function calls – Terminates when base case reached – Slower due to function call overhead • Each call generates new copy of local variables – Easy to read and debug when modeling problem with naturally recursive solution docsity.com