1 / 33

Program Structure II

Program Structure II. Functions Example: Mark s to Grade s Conversion Parameters and Return Statement Use of Variables Comments Flowchart Example: Find Highest Mark Introduction to Variables Use of Local Variables and Global Variables Example: Counter.

Download Presentation

Program Structure II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Program Structure II • Functions • Example: Marks to Grades Conversion • Parameters and Return Statement • Use of Variables • Comments • Flowchart • Example: Find Highest Mark • Introduction to Variables • Use of Local Variables and Global Variables • Example: Counter [Please switch off your phone]

  2. MARKS TO GRADES CONVERSION C B A Introduction to Functions An Example: Marks to Grades Conversion 4 Grades: F: 0-45 C: 46-65 B: 66-80 A: 81-100 65 80 90 • The design: • The header • The table containing marks and grades • The marks, grades, and the button are elements of a form, specified as <input..>. • Marks are text boxes where the user can type: <input type="text" ../> • Grades are read-only text boxes: <input type="text"readonly="readonly" ../> • The button has the name "Convert" (the value attribute). It accepts the onclick event and shows the grades: <input type="button"value="Convert"onclick="…." />

  3. MARKS TO GRADES CONVERSION The code (Page 1): <html> <head><title>CS1301 DEMO</title></head> <body> <h2>MARKS TO GRADES CONVERSION</h2> <form name="F1"> <table border="1"> <tr> <td align="center" style="width:25%">Subject</td> <td align="center" style="width:25%">Chinese</td> <td align="center" style="width:25%">English</td> <td align="center" style="width:25%">Mathematics</td> </tr> <tr> <td align="center">Mark</td> <td align="center"><input type="text" name="CMark" size="4"/></td> <td align="center"><input type="text" name="EMark" size="4"/></td> <td align="center"><input type="text" name="MMark" size="4"/></td> </tr> <tr> <td align="center">Grade</td> <td align="center"><input type="text" name="CGrade" readonly="readonly" size="4"/></td> <td align="center"><input type="text" name="EGrade" readonly="readonly" size="4"/></td> <td align="center"><input type="text" name="MGrade" readonly="readonly" size="4"/></td> </tr> </table> Version 1: By writing inline JavaScript

  4. The code (Page 2): MARKS TO GRADES CONVERSION • The if (..) else .. statements are verbally like spoken english. • But indeed they are a part of programming language ( learn later ). • In this code, '>' is used to compare a string and a number. (Because a textbox value is a string) • In such cases the string is automatically converted to number first so that they can be compared. <input type="button" value="Convert" onclick=" if (document.F1.CMark.value>80) document.F1.CGrade.value='A'; else if (document.F1.CMark.value>65) document.F1.CGrade.value='B'; else if (document.F1.CMark.value>45) document.F1.CGrade.value='C'; else document.F1.CGrade.value='F'; if (document.F1.EMark.value>80) document.F1.EGrade.value='A'; else if (document.F1.EMark.value>65) document.F1.EGrade.value='B'; else if (document.F1.EMark.value>45) document.F1.EGrade.value='C'; else document.F1.EGrade.value='F'; if (document.F1.MMark.value>80) document.F1.MGrade.value='A'; else if (document.F1.MMark.value>65) document.F1.MGrade.value='B'; else if (document.F1.MMark.value>45) document.F1.MGrade.value='C'; else document.F1.MGrade.value='F'; " /> </form> </body> </html> However, such a very long code makes the button’s tag complicated. So, let’s put the code in a function. That will be Version 2 ! ( next slide )

  5. Version 2: By writing a function: SetGrades() MARKS TO GRADES CONVERSION The code: • … • <script type="text/javascript"> • function setGrades( ) • { • if (document.F1.CMark.value>80) • document.F1.CGrade.value='A'; • else if (document.F1.CMark.value>65) • document.F1.CGrade.value='B'; • else if (document.F1.CMark.value>45) • document.F1.CGrade.value='C'; • else • document.F1.CGrade.value='F'; • if (document.F1.EMark.value>80) • document.F1.EGrade.value='A'; • else if (document.F1.EMark.value>65) • document.F1.EGrade.value='B'; • else if (document.F1.EMark.value>45) • document.F1.EGrade.value='C'; • else • document.F1.EGrade.value='F'; • if (document.F1.MMark.value>80) • document.F1.MGrade.value='A'; • else if (document.F1.MMark.value>65) • document.F1.MGrade.value='B'; • else if (document.F1.MMark.value>45) • document.F1.MGrade.value='C'; • else • document.F1.MGrade.value='F'; • } • </script> • <input type="button" value="Convert" onclick="setGrades( );" /> • … Now the button’s tag is simple.

  6. Version 2: By writing a function: SetGrades() MARKS TO GRADES CONVERSION name of the function The contents contained in the function. Explanation: In version 2, the very long code is packaged to form a function: function setGrades( ) { …. …. } • First, we write function, then the function name, and then ( ). • Then, we add the contained code in the function, enclosed within { }. • When we apply a function so as to run its code, we say we “calla function”. • We call a function by its name followed by ( ). • Example: <input type="button" value="Convert" onclick="setGrades( );" />

  7. Version 2: By writing a function: SetGrades() MARKS TO GRADES CONVERSION Is version 2 good enough? • … • <script type="text/javascript"> • function setGrades( ) • { • if (document.F1.CMark.value>80) • document.F1.CGrade.value='A'; • else if (document.F1.CMark.value>65) • document.F1.CGrade.value='B'; • else if (document.F1.CMark.value>45) • document.F1.CGrade.value='C'; • else • document.F1.CGrade.value='F'; • if (document.F1.EMark.value>80) • document.F1.EGrade.value='A'; • else if (document.F1.EMark.value>65) • document.F1.EGrade.value='B'; • else if (document.F1.EMark.value>45) • document.F1.EGrade.value='C'; • else • document.F1.EGrade.value='F'; • if (document.F1.MMark.value>80) • document.F1.MGrade.value='A'; • else if (document.F1.MMark.value>65) • document.F1.MGrade.value='B'; • else if (document.F1.MMark.value>45) • document.F1.MGrade.value='C'; • else • document.F1.MGrade.value='F'; • } • </script> • <input type="button" value="Convert" onclick="setGrades( );" /> • … • In Version 2, • The logic for each subject is actually the same. • The logic is repeated 3 times (very long). • A better way: • Let’s create a short function that simply inputs a mark and outputs a grade, • then we use it once for each subject. • We will do this in Version 3. • (next slide) For Chinese For English For Math

  8. Version 3: Use parameter, return : convertToGrade() MARKS TO GRADES CONVERSION The code: • … • <script type="text/javascript"> • function convertToGrade(mark) • { • var grade; • if (mark>80) • grade='A'; • else if (mark>65) • grade='B'; • else if (mark>45) • grade='C'; • else • grade='F'; • return grade; • } • </script> • <input type="button" value="Convert" onclick=" • document.F1.CGrade.value=convertToGrade(document.F1.CMark.value); • document.F1.EGrade.value=convertToGrade(document.F1.EMark.value); • document.F1.MGrade.value=convertToGrade(document.F1.MMark.value); • " /> • … • convertToGrade says: • “ When you call me, you’ll pass me a mark. • I’ll just name it as mark. • I don’t care about its origination. • “ I’ll set the result using the grade variable. • You’ll get it when I return grade. • I don’t care how you will use it.” • The above “don’t care”s are good: • Not tied to any subject •  we can use the function flexibily. which subject even physics mark, biology mark, ..

  9. Version 3: Use parameter, return : convertToGrade() MARKS TO GRADES CONVERSION markis a parameter : - Refers to the input value that the caller passes into this function. Explanation 1: The Structure of convertToGrade() function convertToGrade(mark) { var grade; if (mark>80) grade='A'; else if (mark>65) grade='B'; else if (mark>45) grade='C'; else grade='F'; return grade; } This return .. statement passes a value back to the caller. • We call this function by its name followed by a value for the parameter in ( ). • Example: • document.F1.CGrade.value =convertToGrade(document.F1.CMark.value);

  10. Version 3: Use parameter, return : convertToGrade() MARKS TO GRADES CONVERSION “Assign a value to an object” function convertToGrade(mark) { } .. return grade; Explanation 2: How convertToGrade() is Used: Consider: document.F1.CGrade.value = convertToGrade(document.F1.CMark.value); • In the above, “=” is called “the assignment operator”. • The whole line is called “an assignment statement”: • - The left-hand-side of “=” is the object whose value is to be changed. • - The right-hand-side of “=” is the value used to change the left-hand-side object. • Don’t mix up left-hand-side and right-hand-side !! • The computer runs 2 steps:   document.F1.CGrade.value = convertToGrade(document.F1.CMark.value); Step : Find the right-hand-side value: ie. Call the convertToGrade function. When it finishes, it will return the grade string. Step : Assign the grade string to left-hand-side (update the Chinese grade) document.F1.CGrade.value =convertToGrade(document.F1.CMark.value); the grade string

  11. Version 3: Use parameter, return : convertToGrade() MARKS TO GRADES CONVERSION Version 2 function setGrades( ) { . } function convertToGrade(mark) { } Logic for Chinese .. return grade; Logic for English Logic for Maths Version 3 Explanation 3: The overall onclick event handler: onclick="document.F1.CGrade.value=convertToGrade(document.F1.CMark.value); document.F1.EGrade.value=convertToGrade(document.F1.EMark.value); document.F1.MGrade.value=convertToGrade(document.F1.MMark.value); " 6 steps: Firstly call convertToGrade for Chinese, then  update Chinese grade. Then call convertToGrade forEnglish, then  update English grade. Then call convertToGrade forMaths, then update Maths grade. convertToGrade will run 3 times totally Why Version 3 is better? Version 2: repeat writing the logic 3 times for the 3 subjects.  To change A from 80 to 85, need to change all 3 If forget one part  inconsistent, error code (bug) More testing work: Need to test all 3  To add one more subject, need to add one more How about 8 subjects? Long, difficult to maintain. Above problems are minimized in Version 3. Called separately for each subject.

  12. Version 4: Nested function call:inside convertAll(), we further run convertToGrade(). MARKS TO GRADES CONVERSION The code: • … • <script type="text/javascript"> • function convertToGrade(mark) • {var grade; • if (mark>80) • grade='A'; • else if (mark>65) • grade='B'; • else if (mark>45) • grade='C'; • else • grade='F'; • return grade; • } • function convertAll( ) • { document.F1.CGrade.value=convertToGrade(document.F1.CMark.value); • document.F1.EGrade.value=convertToGrade(document.F1.EMark.value); • document.F1.MGrade.value=convertToGrade(document.F1.MMark.value); • } • </script> • <input type="button" value="Convert" onclick="convertAll( );" /> • … To further simplify the inline JavaScript for the onclick event, we add the convertAll function: 2 functions: convertToGrade convertAll To handle onclick, we call convertAll, that in turn calls convertToGrade3 times

  13. Quick Revision: MARKS TO GRADES CONVERSION Version 2 Version 1 Version 3 Version 4 … <script ..> function setGrades( ) { } </script> <input type="button" .. onclick="setGrades( );" /> … <input type="button" .. onclick= " " /> • … • <script ..> • function convertToGrade(mark) • { • return grade; • } • </script> • <input type="button" .. • onclick=" • document ..=convertToGrade(..); • document ..=convertToGrade(..); • document ..=convertToGrade(..); • " /> • … • <script ..> • function convertToGrade(mark) • { • return grade; • } • function convertAll( ) • {document ..=convertToGrade(..); • document ..=convertToGrade(..); • document ..=convertToGrade(..); • } • </script> • <input type="button" .. • onclick=" convertAll( ); " • " /> Logic for Chinese Logic for Chinese Logic for any mark Logic for any mark Logic for English Logic for English Logic for Maths Logic for Maths Learn to use parameters and return values - Creates flexible functions Observe : Nested function call - A funciton (convertAll) calls other function(s). • Both Version 3 and Version 4 are good. • “Should we always start like Version 1, then Version 2, ..?” • No. From now on, always start thinking about writing our own functions with proper parameters and return value whenever appropriate. • Very often, we firstly decide how a function will be used. Then we write the functions.

  14. Introduction to Functions • [ Let’s summarize and introduce more ] • Why do we write FUNCTIONS? • Better organization of code. • Functions can be reused: call the same function from different parts. • Eg. Add 5 marks as bonus to all subjects: then we can also call convertAll to update all grades. • One single function can serve different sets of input data values. • (just need to pass the input values through parameters whenever we call the function). • Function Names • Should be descriptive. Bad examples: • Often composed of 2 or more words: first one is a verb, eg. convertAll, showDetails • A common way: First word starts with lowercase, others start with uppercase. • Some other constraints: CANNOT start with 0 - 9. CANNOT be a keyword. Eg. 9To5 and else are wrong • Format of Function Definition:function function_name( parameter-list ) { • ... some code ... • (may or may not return a value) } • To Call a Function:function_name(argument-list) function temp() { .. }  bad names (not meaningful) function Function1() { .. }

  15. Introduction to Functions parameters The showMultiple function "sees" 10, 20 as the values of its parametersa, b. a*b is the product of a and b. arguments showMultiple is called with the arguments10 and 20. Parameters / Arguments function showMultiple(a,b) { alert(a*b); } … showMultiple(10,20); Arguments (eg. 10, 20 here) are the actual values that we pass to the function in the function call, that fit the function parameters(ie. a and b). Arguments and parameters are separated by commas.   Parameter names (a and b) should appear in the function only.  Arguments in the argument-list should match the parameter-list. • Parameters make a function flexible: Can work for different data.

  16. Introduction to Functions The values of a and b are multiplied and then returned. The function is ended immediately. The value of X in the form F1 is set to 200. The value of 242 is shown in an alert dialog box. The return statement • The return keyword tells the browser to return a value from the function definition to the statement that called the function, eg. return 'A'; • After running the returnstatement, the function is stopped immediately, even if there exists any other statement below the return statement. Example: function calculateMultiple(a,b) { return (a*b); } ------------------------------------------------------ document.F1.X.value = calculateMultiple(10,20); alert(calculateMultiple(11,22)); • If you need a function to reply an answer to the caller, don't forget to use return.

  17. Introduction to Functions The return statement Recall: After running the returnstatement, the function is stopped immediately, even if there exists any other statements below the return statement. Example: Therefore, a function can have multiple return statements but only one can run. function convertToGrade(mark) {var grade; if (mark<0) return '[mark too low]'; if (mark>100) return '[mark too high]'; if (mark>80) grade='A'; else if (mark>65) grade='B'; else if (mark>45) grade='C'; else grade='F'; return grade; }  At the beginning of the function, handle special cases first. return … : pass the special result back to the caller and stop the function.  If the mark is abnormal, the function is stopped by  already. Therefore, here we need not worry about any abnormal mark.

  18. Introduction to Functions Note that, if the function gets more complicated, then we should avoid multiple use of return in a confusing way. Because it will be difficult to read (not sure whether a part of the code already terminates the function). Recall: After running the returnstatement, the function is stopped immediately, even if there exists any other statements below the return statement. We can rewrite convertToGrade: • function convertToGrade(mark) • { var grade; • if (mark>80) • grade='A'; • else if (mark>65) • grade='B'; • else if (mark>45) • grade='C'; • else • grade='F'; • return grade; • } function convertToGrade(mark) {if (mark>80) return 'A'; else if (mark>65) return 'B'; else if (mark>45) return 'C'; else return 'F'; } if (..) if (..) return .. else if (..) if (..) .. else return .. else .. If (..) return.. else return.. Original OK function convertToGrade(mark) {if (mark>80) return 'A'; if (mark>65) return 'B'; if (mark>45) return 'C'; return 'F'; } Headache OK

  19. Introduction to Functions • It is not a must to write a return value in the return statement. • Depend on the situation, we may write: return [a value]; • Or just return; • function convertAll( ) • { • if (document.F1.CMark.value=="" || document.F1.EMark.value=="" || document.F1.MMark.value=="" ) • { alert("Please input all marks"); • return; • } • document.F1.CGrade.value=convertToGrade(document.F1.CMark.value); • document.F1.EGrade.value=convertToGrade(document.F1.EMark.value); • document.F1.MGrade.value=convertToGrade(document.F1.MMark.value); • } • Explanation: • The if-statement says: "IF Chinese mark is empty OR English mark is empty OR Mathematics mark is empty". • If this is the case, then show a message box and immediately stop the function by return; • There is no value to return to the caller, so we type "return;" • || means "OR"== means "IS EQUAL TO""" (2 double quotes: “”) means empty • To include 2 statements within the if-statement, we need to enclose them with { and }. • If we omit these pair of { and }, then "return;" won't be limited to the if-statement anymore. So it is executed no matter whether the if(..) condition is true or not  function stops here anyway. • Try!

  20. Introduction to Functions Comments • <script type="text/javascript"> • /* convertToGrade - returns a grade based on input mark */ • /* assumption : user input is within 0-100 */ • function convertToGrade(mark) • {if (mark>80) //for the range 81-100 • return 'A'; • else if (mark>65) //for the range 66-80 • return 'B'; • else if (mark>45) //for the range 46-65 • return 'C'; • else //for the range 0-45 • return 'F'; • } • /* convertAll - update all grade boxes based on the marks. • grades are obtained by calling convertToGrade • */ • function convertAll( ) • { document.F1.CGrade.value= • convertToGrade(document.F1.CMark.value); • document.F1.EGrade.value= • convertToGrade(document.F1.EMark.value); • document.F1.MGrade.value= • convertToGrade(document.F1.MMark.value); • } • </script> Adding Comments in JavaScript • It is a good practice to add comments for explaining what the program does. • The JavaScript interpreter ignores any text marked as comments. • Two types of JavaScript comments: • Single-line comments start with two slashes (//) and are limited to one line. • Multiple-line commentsstart with /* and end with */ • Note that they are different from HTML comments: <!--..-->

  21. Introduction to Functions Different formats of the “ if..else if .. else if .. else ” logic • There are 2 styles for if-else-if statements if-else ladder (parallel situations) If-else staircase • if (mark>80) • grade='A'; • else • if (mark>65) • grade='B'; • else • if (mark>45) • grade='C'; • else • grade='F'; • if (mark>80) • grade='A'; • else if (mark>65) • grade='B'; • else if (mark>45) • grade='C'; • else • grade='F'; Each “else” aligns with the corresponding “if”. Simply list the different cases in a parallel way. • The computer runs the above in the same way (next slide). • Always choose only one of the above formats • - Don’t use both together (eg. one style for grades A, B; another style for C, F). • - As the 4 cases above have “parallel” relationship, so the ladder style is better for them. • Don’t put semi-colon after if(..) and else. [ Learn more later ] if (mark>80); else;  

  22. True False True False True False Beginning / End Flowchart Symbols Explanation Selection Process / Assignment Input / Output Flow Flowchart We often use Flowcharts to represent the logics of our code: • function convertToGrade(mark) • { var grade; • if (mark>80) • grade='A'; • else if (mark>65) • grade='B'; • else if (mark>45) • grade='C'; • else • grade='F'; • return grade; • } Start mark >80 Set grade to 'A' mark >65 Set grade to'B' mark >45 Set grade to'C' Set grade to'F' return grade End

  23. Flowchart Start  True mark >45 Set grade to 'C' False  mark >65 True Set grade to'B' False  mark >80 True Set grade to'A' False  Set grade to'F' return grade End • if (mark>45) • grade='C'; • else if (mark>65) • grade='B'; • else if (mark>80) • grade='A'; • else • grade='F';     It is wrong to change the order of cases: C, B, A, F • function convertToGrade(mark) • { var grade; • if (mark>45) • grade='C'; • else if (mark>65) • grade='B'; • else if (mark>80) • grade='A'; • else • grade='F'; • return grade; • }  In the code above, any mark within 46-100 will get 'C' grade only. For example, if the mark is 90, then  is correct, so the grade is set to 'C'. The else part - will not execute.  Finally the grade will be 'C' only. (This can also be observed from the flowchart.)

  24. mark >80 True Set grade to 'A' False  mark >65 True Set grade to'B'  False    mark >45 True False  Set grade to'F' End Flowchart It is also wrong to omit "else" for grades 'B' and 'C': • function convertToGrade(mark) • { var grade; • if (mark>80) • grade='A'; • if (mark>65) • grade='B'; • if (mark>45) • grade='C'; • else • grade='F'; • return grade; • } Start  Set grade to'C' In the code above, no matter whether the mark is high or low (ie. 90 or 30), statement  will be executed. Then it carries out either  or  to change the grade to C or F.  Finally the grade wouldnever be 'A' or 'B'. return grade

  25. Find Highest Mark Another Example: Find Highest Mark After the user has input the marks and clicked the button, the marks are compared and the highest mark is shown. Question: How to find the highest mark? An approach: 1. Use a variablehm to represent the result. 2. Set hm to Chinese mark first. 3. If English mark is higher than hm, override hm with English mark. 4. If Maths mark is higher than hm, override hm with Maths mark. 5. Finally the value of hm is the highest mark.

  26. <form name="F1"> <table border="1"> … <tr> <td align="center">Mark</td> <td align="center"><input type="text" name="CMark" size="4"/></td> <td align="center"><input type="text" name="EMark" size="4"/></td> <td align="center"><input type="text" name="MMark" size="4"/></td> </tr> </table> … Find Highest Mark … <script type="text/javascript"> function findHighestMark() { var hm; hm=parseInt(document.F1.CMark.value); if (parseInt(document.F1.EMark.value)>hm) hm=parseInt(document.F1.EMark.value); if (parseInt(document.F1.MMark.value)>hm) hm=parseInt(document.F1.MMark.value); alert(hm); } </script> <input type="button" value="FindHighestMark" onclick="findHighestMark( );" /> … • What if we don't use parseInt at all? Let's write "if (document.F1.EMark.value>hm)" etc.. and try the marks 30,40,100. Result: 40 will be highest mark. Reason: the values are stored as characters. If '>' is applied to 2 character strings, they will not be converted to numbers automatically. Just like 'baby' is after 'ax' in dictionary, the character '4' is after '1'. So '40' is larger than '100'!!

  27. Find Highest Mark Self-revision Exercise It is wrong to design the code as follow:  function findHighestMark() { var hm; hm=parseInt(document.F1.CMark.value); if (parseInt(document.F1.EMark.value)>hm) hm=parseInt(document.F1.EMark.value); else if (parseInt(document.F1.MMark.value)>hm) hm=parseInt(document.F1.MMark.value); alert(hm); } Try the following input: Chinese: 65 English: 85 Mathematics: 95 You can observe a wrong output Your task: (1) Draw flowcharts for the original version and this wrong version. (2) Explain why this version is wrong.

  28. Variables .. .. .. x y z Introduction to Variables Variable declaration using the varkeyword: Example: var hm; var x,y,z; In the above,hm, x, y, zare declared as variables. Each variable refers to a location in the memory. Before assigning any value, the variable is undefined. Example: “javascript: var x; alert(x);” shows “undefined” computer's memory: 80 90 hm Set hm ’s value using "=" (assignment operator) : Example 1:hm=80; store the number 80 at the memory location referred by hm. Example 2:hm=document.F1.Cmark.value; Suppose Chinese mark is 90, then 90 is stored at the memory location referred by hm. Use the value of hm: For short, we say "hm is equal to [the value at the memory location referred by hm]". Example: Suppose 90 is the value stored there, then we say "hm is equal to 90". In the program, suppose the value is needed, then we simply write hm.Note: not 'hm' Example: "alert(hm)" shows the value in an alert dialog box.

  29. Local and Global Variables Global variables: a, b, and c. Local variables:x, y, and z. Introduction to Variables Local variables vs Global variables function some_function() { var x; var y,z; .. } var a,b,c; • Local variables: declared inside a function • Each time when a function starts, memory locations are assigned to local variables. • After the function has finished, the local variables are no longer valid. • When the same function is called the second time, memory locations are assigned to its local variables again. • Global variables: declared outside a function • Global variables are assigned with memory locations when the web page is loaded. • All global variables persist until the page is closed.

  30. <script type="text/javascript"> var a,b,c; //Global variables //a function that sets the values of a,b,c and its local variables x,y,z function some_function() { var x; //local variables var y,z; x=1; y=2; z=3; a=10; b=20; c=30; } </script> Demonstration Local and Global Variables <!-- A pseudo-URL that calls some_function and then shows the global variables only --> <a href="javascript: some_function(); alert( 'a is ' + a + ', ' + 'b is ' + b + ', ' + 'c is ' + c );" > test a,b,c only</a> <!-- A pseudo-URL that calls some_function and then shows all variables --> <a href="javascript: some_function(); alert( 'a is ' + a + ', ' + 'b is ' + b + ', ' + 'c is ' + c + ', ' + 'x is ' + x + ', ' + 'y is ' + y + ', ' + 'z is ' + z );" >test all a,b,c,x,y,z</a> OK Recall: After the function has finished, the local variables (x,y,z) are no longer valid.

  31. Local and Global Variables 1 2 1 1 2 2 1 2 3 Introduction to Variables An Example: COUNTER (Demonstration of global variable) • A pseudo-URL calls a function, count, to add 1 to the count and show the count. • A global variable,c,is used to keep track of the count. • The value of cpersists after each time the count function adds 1 to it. • ( Though we can also use innerHTML of HTML elements to hold values, but using Javascript's variables is more flexible and gives faster access speed.)

  32. Local and Global Variables COUNTER (Demonstration of global variable) • 1 • 2 • 3 • 4 • 5 • 6 • <html> • <head> • <title>CS1301 DEMO</title> • </head> • <body> • <script type="text/javascript"> • var c=0; • function count( ) • { • c=c+1; • document.getElementById("counter").innerHTML=c; • } • </script> • <a href="javascript:count( );">Add 1 to the counter</a>: • <br/> • <span id="counter"></span> • </body> • </html> • What if we change the variable c to local (ie. move line 1 to line 3)? Result: It will show 1 every time. Reason: When the function is ended, c does not persist anymore. Next time when the function starts again, c will be assigned to another new memory location. Every time when the function starts, c is set to zero and added with 1.

  33. Summary • Functions and Variables • Introduction to Functions • Example: Marks to Grades Conversion • FORM: Get data from a text box and • Put values into a read-only text box • Function Declaration and Calling a function • Parameters and Return Statement • Nested Function call • Comments • Flowchart • Example: Find Highest Mark • Introduction to Variables • Use of Local Variables and Global Variables • Example: Counter

More Related