Functions Assignment #2 Revision is now due on Tuesday, May 24th 2 Basic Functions NOTE: There are an awful lot of synonyms for "function" "routine, map […], procedure, […], subroutine, […], subprogram, […], function" From http://www.synonyms.net/synonym/function: Also "Method" 3 Basic_JS_Function.html The UI (User interface) is pretty straight-forward: when you click on the first button two alert boxes pop up. Clicking the second button pops just one alert. The HTML is pretty much just boilerplate code 4 Basic functions: Basic_JS_Function.html: Named functions 1 () { function MyNamedFunction alert("You clicked on a button, and this\nNAMED\nfunction was run to handle the event!"); } $(document).ready( function () { // note that this is an anonymous function $("#anon").click( function () { // this is another anonymous function alert("You clicked on a button, and this\nANONYMOUS\nfunction was run to handle the event!"); MyNamedFunction(); }); $("#normal").click( MyNamedFunction ); // Note that there are NO ()'s at the end of the name!!! }); • Arrow #1: This will define a new function, with the name MyNamedFunction • function MyNamedFunction() { = • Function = This is how we tell JavaScript that we want to create a new function • MyNamedFunction = We chose this name for our function • () = These are required • { } = These mark the start and end of the function 5 Basic functions: Basic_JS_Function.html: Named functions () { 2 function MyNamedFunction alert("You clicked on a button, and this\nNAMED\nfunction was run to handle the event!"); } $(document).ready( function () { // note that this is an anonymous function $("#anon").click( function () { // this is another anonymous function alert("You clicked on a button, and this\nANONYMOUS\nfunction was run to handle the event!"); MyNamedFunction(); }); $("#normal").click( MyNamedFunction ); // Note that there are NO ()'s at the end of the name!!! }); • • • • #2: The body of the function goes here. When the function is called the body is executed, and then execution returns to whichever line called the function. If there's more than 1 line then we go from top to bottom In this case it's just a single line: alert 6 Basic functions: Basic_JS_Function.html: Named functions 1 () { function MyNamedFunction alert("You clicked on a button, and this\nNAMED\nfunction was run to handle the event!"); } $(document).ready( function () { // note that this is an anonymous function $("#anon").click( function () { // this is another anonymous function alert("You clicked on a button, and this\nANONYMOUS\nfunction was run to handle the event!"); 3 MyNamedFunction(); }); $("#normal").click( MyNamedFunction ); // Note that there are NO ()'s at the end of the name!!! }); • #3: This is where we call the function • The program should jump from #3 to the definition ( #1 ), execute the body of the function from top to bottom, and then return here to #3 • MyNamedFunction(); = We list the name of the function (MyNamedFunction) and then MUST include the parentheses (() ). The semi-colon (; ) is optional but normally it is listed. 7 Basic functions: Basic_JS_Function.html: Named functions 1 3 4 function MyNamedFunction() { alert("You clicked on a button, and this\nNAMED\nfunction was run to handle the event!"); } $(document).ready( function () { // note that this is an anonymous function $("#anon").click( function () { // this is another anonymous function alert("You clicked on a button, and this\nANONYMOUS\nfunction was run to handle the event!"); MyNamedFunction(); }); $("#normal").click( MyNamedFunction ); // Note that there are NO ()'s at the end of the name!!! }); • #4: This is where we tell jQuery to use the function as the event handler • Note that we are NOT calling it here – we're just telling jQuery to use it • $("#normal").click( … ); = We set up the jQuery event handler for the button being clicked, like you've seen before • MyNamedFunction = name of the function to use. • NOTE: We do NOT put parentheses here. • We put parentheses next to the function when defining it ( #1) or calling it (#3) 8 Basic functions: Basic_JS_Function.html: ANONYMOUS functions () { function MyNamedFunction alert("You clicked on a button, and this\nNAMED\nfunction was run to handle the event!"); } $(document).ready( function () { // note that this is an anonymous function 5 $("#anon").click( function() { // this is another anonymous function alert("You clicked on a button, and this\nANONYMOUS\nfunction was run to handle the event!"); MyNamedFunction(); }); $("#normal").click( MyNamedFunction ); // Note that there are NO ()'s at the end of the name!!! }); • #5: This is one example of an anonymous function. Note that it's basically the same as the named function except with the name of the function left out (because there is no name of the function). • The key part is: • function() { … } = Where … is the body of the function 9 Basic functions: Basic_JS_Function.html: ANONYMOUS functions () { function MyNamedFunction alert("You clicked on a button, and this\nNAMED\nfunction was run to handle the event!"); } 5 6 that this is an anonymous function { // note function() { // this is another anonymous function $(document).ready( function() $("#anon").click( alert("You clicked on a button, and this\nANONYMOUS\nfunction was run to handle the event!"); MyNamedFunction(); 5 }); $("#normal").click( MyNamedFunction ); // Note that there are NO ()'s at the end of the name!!! });6 • #6: This is another example of an anonymous function. 10 Work on Exercise #1 for this part of this lecture 11 Functions: Local vs. Global Variables Let's look at Local_Vs_Global_Vars.html 12 1 2 <script type="text/javascript"> // … Stuff left out to make this all fit on the slide w = 1; var x = 1; Local_Vs_Global_Vars.html function Vars(){ var y = 1; if (x == 1) { z = 1; // global on purpose // z is create here, but is ACTUALLY GLOBAL!!! alert("Creating z"); } alert("the current value of w is: " + w + "\nthe current value of x is: " + x + "\nThe current value of y is: " + y + "\nThe current value of z is: " + z); w = w + 1; x = x + 1; y += 1; // same as "y = y + 1"; alert("AFTER:\nthe current value of w is: " + w + "\nthe current value of x is: " + x + "\nThe current value of y is: " + y + "\nThe current value of z is: " + z); z++; // increases z by one; z-- decreases z by one 4 } 3 1. w and x are globals because they're inside the <script> element but OUTSIDE any functions 2. Y is local because it is INSIDE a function Note that we can access global variables (like x) inside the function 3. We just start using the 'z' variable without using the keyword var first. This will create 'z' as a global variable. • If we put the "use strict" at the top of the script then the browser would flag this as an error 4. Note that we change both the w and x global variables and the y local variable. When we click the button again you'll see that the globals have kept their value from last time, while the local variable gets reset. 13 Functions: Parameters and Return Values 14 Params_Return_Values.html The page uses a straightforward AddTwoNumbers function which takes two numbers, adds them together, and returns the result to the event handler The function provides no error handling, etc, whatsoever. 15 Params_Return_Values.html: Parameters and return values • The HTML is pretty straightforward • We'll first look at the event handler… • …then look at the new function 16 Params_Return_Values.html: Parameters and return values 1 2 $(document).ready( function() { $("#functionDemo").click( function() { // var smaller = parseFloat( $("#num1").val() ); // var larger = parseFloat( $("#num2").val() ); var smaller = Number( $("#num1").val() ); var larger = Number( $("#num2").val() ); • #1: Notice that we're setting up anonymous functions to react to the document being ready, and to handle the button click • #2: • $("#num1").val() = We're going to get whatever the user typed into the textbox • Number() = then convert that to a number. This has the same effect as parseFloat • var smaller = = then assign that to a newly created variable 17 Params_Return_Values.html: Parameters and return values 3 4 … var result; if( isNaN(smaller) || isNaN(larger) ) { result = "Error! Either " + smaller + " or " + larger + " is not a number (or both aren't!)"; } else { // result = smaller + larger; result = AddTwoNumbers( smaller, larger ); } • #3: If the user didn't give us valid input then provide an error message: • var result; = Create a new variable named result • isNaN(smaller) || isNaN(larger) = check if either one (or both) aren't numbers • if(…) { result = "Error! Either " + smaller + " or " + larger + " is not a number (or both aren't!)"; } = If either isn't a number then build up that error message to use as our result • #4: Otherwise call the function • AddTwoNumbers( … ) = Call the function • smaller, larger = send smaller and larger into the function, so that the function can use it • result = = Whatever the function returns, assign that to the result variable 18 Params_Return_Values.html: Parameters and return values … var output = ""; 5 output += "Output starts here: <br/>"; output += result + "<br/>"; output += "That's all, folks!"; 6 $("#output").html( output ); }); }); • • #5: Use the 'accumulator' pattern to build up the output string #6: Display the output string on the web page • Next, let's look at the function itself 19 7 Params_Return_Values.html: Parameters and return values function AddTwoNumbers( numA, numB) { // Note that because this "result" is local to this function // it is a DIFFERENT variable that the "result" used in the // "click" function, below // alert( numB ); var result = numA + numB; 8 9 return result; // could be done more compactly as: // return numA + numB; } • • • #7: This is mostly the same as the prior 'named function' example. What's new is that this one has parameters • function AddTwoNumbers( numA, numB) { = Whatever's listed first on the calling side is refered to as numA here, whatever's listed second is listed at numb #8: Add the two numbers together, and store them into a local variable named result • Note that this is completely separate from the variable named "result" in the event handler #9: This tells JS which value to return from the function 20 Work on Exercise #2 for this part of this lecture 21 Functions: Using the accumulator pattern Let's look at Functions_Accumulator.html 22 Work on Exercise #2 for this part of this lecture 23 Accumulator Pattern 24 How to accumulate a complete string of output $("#accumulatorExample").click( function (){ // string starts out empty var outputString = ""; var input = $("#name").val(); // Add the start & end tags for "bold" element outputString += "Your name: <b>" + input + "</b><br/>\n"; input = $("#flavor").val(); outputString += "Favorite flavor:<i>" + input + "</i><br/>"; // for debugging (troubleshooting) purposes: alert(outputString); $("#output").html( outputString ); }); • This will get the user's input for both their name and their favorite ice cream flavor, and then display those results on the page 25 How to accumulate a complete string of output $("#accumulatorExample").click( function (){ // string starts out empty 1) var outputString = ""; Value of outputString 1 2) var input = $("#name").val(); 3) // Add the start & end tags for "bold" element outputString += "Your name: <b>" + input + "</b><br/>\n"; 4) 5) input = $("#flavor").val(); outputString += "Favorite flavor:<i>" + input + "</i><br/>"; 6) // for debugging (troubleshooting) purposes: alert(outputString); 7) $("#output").html( outputString ); "" }); • Step #1 • Create a new string variable, and make sure that it starts out empty • var outputString = ""; 26 How to accumulate a complete string of output $("#accumulatorExample").click( function (){ // string starts out empty 1) var outputString = ""; 2) var input = $("#name").val(); // Add the start & end tags for "bold" element 3) outputString += Value of outputString 1 "" 2 "" 3 "Your name: <b>Mike</b><br/>\n" (I'm going to assume that Mike was typed into the text box) "Your name: <b>" + input + "</b><br/>\n"; • Repeat these Steps: = • var input = $("#name").val(); = Get the user's input • outputString += "Your name: <b>" + input + "</b><br/>\n"; = glue the next blob of text onto the ouputString variable. • Make sure to use the += operator • X += 2 is the same as X = x + 2 27 Value of outputString How to accumulate a complete string of output $("#accumulatorExample").click( function (){ // string starts out empty 1) var outputString = ""; 2) var input = $("#name").val(); // Add the start & end tags for "bold" element += 3 "Your name: <b>Mike</b><br/>\n" 4 "Your name: <b>Mike</b><br/>\n" 5 "Your name: <b>Mike</b><br/>\nFavorite flavor:<i>Mint</i><br/>" 3) outputString "Your name: <b>" + input + "</b><br/>\n"; (I'm going to assume that 4) 5) input = $("#flavor").val(); outputString += "Favorite flavor:<i>" + input + "</i><br/>"; Mint was typed into the text box) • Repeat these Steps: = • input = $("#flavor").val(); = Get the user's input • outputString += "Favorite flavor:<i>" + input + "</i><br/>"; = glue the next blob of text onto the ouputString variable. 28 Value of outputString How to accumulate a complete string of output $("#accumulatorExample").click( function (){ // string starts out empty var outputString = ""; var input = $("#name").val(); 5 "Your name: <b>Mike</b><br/>\nFavorite flavor:<i>Mint</i><br/>" 6 "Your name: <b>Mike</b><br/>\nFavorite flavor:<i>Mint</i><br/>" // Add the start & end tags for "bold" element outputString += "Your name: <b>" + input + "</b><br/>\n"; 7 "Your name: <b>Mike</b><br/>\nFavorite flavor:<i>Mint</i><br/>" 5) input = $("#flavor").val(); outputString += "Favorite flavor:<i>" + input + "</i><br/>"; 6) // for debugging (troubleshooting) purposes: alert(outputString); 7) $("#output").html( outputString ); }); • Last Steps • alert(outputString); = display the text in an alert, so that we can see exactly what the string looks like 29 • $("#output").html( outputString ); = Display on page Work on Exercise #3 for this part of this lecture 30 Functions: Using Functions In The Branching Adventure First we'll look at one version of this, then you'll modify a slightly different one 31 Work on Exercise #3 for this part of this lecture 32