1 / 21

Program Structure III

Program Structure III. Insertion of Semicolons (;) Location of JavaScript Blocks Names of Variables and Functions Enclose statements in Braces { and } Assignment Statements Data Types (Numbers, Strings, Booleans) and Operations. [Please switch off your phone]. The mystery of Semicolons (;).

bonitae
Télécharger la présentation

Program Structure III

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 III • Insertion of Semicolons (;) • Location of JavaScript Blocks • Names of Variables and Functions • Enclose statements in Braces { and } • Assignment Statements • Data Types (Numbers, Strings, Booleans) and Operations [Please switch off your phone]

  2. The mystery of Semicolons (;) Example: a = 3; b = 4; • Semicolons (;) are used to separate statements from each other. • Can be omitted if each statement is on a separate line. • a = 3 b = 4 • a = 3 b = 4 • a = 3; b = 4; • The fact: JavaScript automatically inserts semicolons if the line seems to be complete. a = 3 b = 4 alert(a+b) a = 3; b = 4; alert(a+b); The invisible semicolons are automatically inserted. //calculate average of marks: var a = ( parseInt(document.F1.CMark.value) + parseInt(document.F1.EMark.value) + parseInt(document.F1.MMark.value)) / 3 alert(a) //calculate average of marks: var a = ( parseInt(document.F1.CMark.value) + parseInt(document.F1.EMark.value) + parseInt(document.F1.MMark.value)) / 3; alert(a); • But manually adding semicolon is a common practice. (In Java, C .., adding semicolon is a must. Most programmers have adapted this rule already) • Sometimes we get trouble if we handle line break or semicolon with mistake. Don’t rely on the automatic insertion of semicolons. ( An interesting discussion is available – see Helpdesk’s hot questions at the course web)

  3. Location of JavaScript Blocks <html> <head> <title>Demo</title> </head> <body> .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. </BODY> </html> • There can be more than 1 JavaScript blocks. • JavaScript blocks can be in : • <head> </head>, and • <body> </body> • Global variables and functions declared in one block can be accessed from other locations. • Eg., the previous Counter example. • Try out: Add 10 to the counter(add a add10() function in a new JavaScript block) • Global variables and functions are normally created in <head>..</head>. • Reason: • The browser loads everything in the <head> tag before it starts executing any JavaScript. • That means, if we put global variables and functions in <head>, then they can be used immediately when the page begins to load. • (2) Easier to lookup. <SCRIPT LANGUAGE=javascript> … … </SCRIPT> <SCRIPT LANGUAGE=javascript> … … </SCRIPT> <SCRIPT LANGUAGE=javascript> … … </SCRIPT>

  4. keywords, variables, function names Names of Variables and Functions • JavaScript is case-sensitive. Example: the if keyword must not be typed as If. • Can consist of any letter, digit, and underscore (_). • Cannot be started with a digit. Example: 9To5 is NOT valid. • Cannot be a JavaScript keyword. Examples: break do function null typeof case elseifreturnvar continue export import switch void default false in this while delete for new true with • Should be descriptive. Bad examples: Function1, temp. • Function names are generally composed of more than one word: first one is a verb. • A common way: First word starts with lowercase, others start with uppercase. Examples: calculateAverage, showRecordDetails camelCase

  5. Actually happens very often Names of Variables and Functions • Using the same variable name locally in 2 or more functions is Okay. • Don’t create global variables just because of “saving local variables” The uses of such a variable become difficult to track ( bad coding style, create bugs easily ) • <SCRIPT LANGUAGE=javascript> • function convertToGrade(mark) • { • var result; • if (mark>80) • result='A'; • else if (mark>65) • result='B'; • else if (mark>45) • result='C'; • else • result='F'; • return result; • } • function convertToPassFail(mark) • { • var result; • if (mark>45) • result='Pass'; • else • result='Fail'; • return result; • } • </SCRIPT> • <SCRIPT LANGUAGE=javascript> • var result; • function convertToGrade(mark) • { • if (mark>80) • result='A'; • else if (mark>65) • result='B'; • else if (mark>45) • result='C'; • else • result='F'; • return result; • } • function convertToPassFail(mark) • { • if (mark>45) • result='Pass'; • else • result='Fail'; • return result; • } • </SCRIPT> When to use local / global variables? Use local variable – when we use the variable only within the function and no need to keep it after the function stops. * Use global variable – only when necessary / appropriate (see previous “Counter” example) * “return result;” actually means Topass back the value ofthe variable result, NOTto pass back the variable result. ie. the variable result is no longer required after “return result;”.  

  6. In f1, x is 3 Call f1() Just alert it undefined Names of Variables and Functions ? What happens if a local and a global variables have the same name.. <html> <head> <title>Demo</title> <SCRIPT LANGUAGE=javascript> var x; function f1( ) { var x; x=3; alert("In f1, x is " + x); } </SCRIPT> </head> <body> <a href="javascript:f1( );">Call f1( )</a> <br/> <a href="javascript:alert(x);">Just alert it</a> </body> </html> The function can see the local x only, not the global x. The function sets the local x to 3, it doesn’t set the global x. • To avoid confusion, we usually DON'T use the same name for local and global variables.

  7. What is your mark? 80 Passed. You must take this course again! Passed. Other Basics about JavaScript Enclose statements in braces { and } var mark; mark=prompt('What is your mark?',''); if (mark>40) document.write('Passed'); else document.write('Failed.'); document.write('<br/>'); document.write('You must take this course again!'); Although last 3 lines are aligned at the same column, JavaScript does not know that they are 'together'. In such case we add {and} to group them together: Wrong output var mark; mark=prompt('What is your mark?',''); if (mark>40) document.write('Passed.'); else { document.write('Failed.'); document.write('<br/>'); document.write('You must take this course again!'); } Correct

  8. Other Basics about JavaScript Enclose statements in braces { and } • How do we indent { and } ? The following 2 ways are recommended: var mark; mark=prompt('What is your mark?',''); if (mark>40) document.write('Passed.'); else { document.write('Failed.'); document.write('<br/>'); document.write('Take this course again!'); } var mark; mark=prompt('What is your mark?',''); if (mark>40) document.write('Passed.'); else{ document.write('Failed.'); document.write('<br/>'); document.write('Take this course again!'); } } -- should align with “else” { -- should align with }or after “else”

  9. Right-hand-side Left-hand-side Assignment Statements • Assignment statement (=) : Assign a value to a variable (or object property, eg. innerHTML) • Example: var msg, a; • msg = "How are you?"; • a = 100; document.getElementById(‘chn’).innerHTML =‘A’; document.F1.result.value = a + b; • Assign a value at the same timewhen a variable is declared: • Example: var x=4, msg="How are you?"; • More powerful assignment operators for numbers. • Example: salary+=100; salary = salary + 100;are the same. •  counter +=1; counter=counter+1; are the same. • Similar ones are : -=, *=, /=, %=

  10. See week 3 tutorial Data Types • Data Types: the type of values that can be handled in a programming language. • 3 JavaScript primitive types: (1) numbers : whole integers (eg. -3, 0, 104, but not “123”) floating-point values (eg. -0.001, 3.1416, but not “12.3”), NaN (not a number) Infinity (2) strings of text - Textbox, innerHTML, prompt dialog’s result, “…”, and ‘…’ (3) booleans (true/false)- learn later! • 2 special values (not belong to any one common type): null: means no value. Example: If no element is called 'a', then document.getElementById('a') gives null. undefined: means a variable that has been declared but never had a value assigned to it. ie. its value is still undefined. Example: var x; alert(x); shows undefined.

  11. Data Types Numbers • Can also be represented as Hexadecimal values: 0x..or 0X.., • eg. var x; x=0xFF; - set x to 255(10) [ie. 15*16+ 15] • alert(0xFF);- display 255 • Can also be represented as Octal values: 0.. [ Be careful: 0123  123 ] • eg. var x; x=0123; - 0123 is handled as 83(10)[ie. 1*8*8+ 2*8 + 3] • alert(0123); not 123(10)!! [123 is 1*100 + 2*10+3] • Common operators for numbers: +, -, *, /, % • Precedence of *, /, and % are higher than + and -. • Example: 3-2*4 gives -5 (* is calculated before -). • Parentheses ( and ) can be used for more complicated calculations. • Example: final_mark = (assignment_mark + (testA + testB)/2)/2 * 0.3 + exam_mark * 0.7; • 2 special operators: ++and--: increment and decrement a variable by 1. • Example: count++; is the same as count = count + 1;andcounter += 1; • count--; is the same as count = count - 1;andcounter -= 1;

  12. Data Types Booleans • A Boolean value is either true or false (cf. a numberic value maybe 1, 100, -1, 3.14, …). • true is equivalent to 1 and false is equivalent to 0. Often used in Decision Making: Equality and Relational Operators • To obtain true / false values based on comparison results: a Boolean value can only be true or false Sample JavaScript conditionMeaning of JavaScript condition Equality operators x == y x is equal to y  x != y x is not equal to y Relational operators x > y x is greater than y x < y x is less than y x >= y x is greater than or equal to y x <= y x is less than or equal to y The results could only be true / false (Boolean values)

  13. true or false Each if (..) actually checks a Boolean value. May simply write : if (all_passed) alert('Congradulations!...'); Data Types Use of Boolean values in an if-statement is often implicit. Example: The code below checks whether a student has passed all of the 3 subjects. var all_passed; all_passed = true; if (english_mark < 46) all_passed = false; if (chinese_mark < 46) all_passed = false; if (maths_mark < 46) all_passed = false; if (all_passed == true) alert('Congradulations! You pass all subjects.'); Note: "= =" - compares the left-hand-side and right-hand-side - it does not change the value of anything. "=" - changes the value of the left-hand-side object (according to right-hand-side) - it does not compare any value.

  14. side1 side2 side3  Don’t write if (side1 == side2== side3) Data Types Decision Making: Logical Operators To perform Boolean algebra. Logical AND : && Logical OR : || Logical NOT : ! if ( (english_mark >= 81) && (chinese_mark >= 81) && (maths_mark >= 81) ) alert('Well done! All distinction!'); * Try adding it to the"MARKS TO GRADE CONVERSION" example (replace english_mark with document.F1.EMark.value etc..) Checking of Equilateral Triangle: if ( side1 == side2&&side2==side3) alert('Equilateral triangle');

  15. Data Types Decision Making: Logical Operators To perform Boolean algebra. Logical AND : && Logical OR : || Logical NOT : ! Combine Left-hand-side and Right-hand-side Boolean arguments (operands) to give Boolean result Only a right-hand-side argument (operand).Give its reversed value. var all_passed = true; if ( (english_mark < 46) || (chinese_mark < 46) || (maths_mark < 46) ) all_passed = false; if (all_passed==false) alert('Sorry! You cannot pass all subjects.'); Same as: if (all_passed != true) alert('Sorry! You cannot...'); May also be simplified as: if ( ! all_passed) alert('Sorry! You cannot...');

  16. She said: "I don't understand!" Data Types • Strings • Strings are sequences of letters, digits, punctuation characters, .. • Can be enclosed in matching pairs of single or double quotes. • Examples: alert('programming is fun'); • alert("programming is fun"); • To include a single quote in a string, enclose it with double quotes.Example: alert("You're very nice"); • To include a double quote in a string, enclose it with single quotes.Example: alert('She said: "I am Happy". '); • Question: how to display this string:

  17. She said: "I don't understand!" Data Types • Strings • Question: how to display this string: An approach: alert( 'She said: "I don' + "'" + 't understand!" ' ); Explanation: ‘She said: “I don’ : a double quote in ' … ' (a pair of single quotes). “’” : a single quote in " … " (a pair of double quotes). ‘t understand!”’ : a double quote in ' … ' (a pair of single quotes).

  18. 'means beginning of the string 'means end of the string \' is treated as the single quote character in the string,not to mean end of string. Data Types Escape Sequences A method to represent special characters by combining backslash (\) with another character: Escape sequenceDescription \n new line \t tab \\ backslash \" Double quote \' Single quote “Escape away” from normal interpretation. -- to produce special effect Example:alert( 'I\'m Happy!');

  19. Data Types Conversions between numbers and strings: • toString : convert a number to a string with a given radix. Example: (45).toString(16) means to convert 45 to hexadecimal, giving "2d". x.toString(16) means to convert the value of variable x to hexadecimal. x.toString(2) means to convert it to binary. • toFixed: convert a number to a string a specific number of digits to the right of the decimal. Example: var x=5/3; x.toFixed() gives 2 x.toFixed(1) gives 1.7 x.toFixed(2) gives 1.67

  20. Data Types Conversions between numbers and strings: • parseInt: convert a string to an integer (with an optional radix). Example: parseInt("100") gives 100 parseInt("3.14 meters") gives 3 parseInt("0xFF") (convert hexadecimal number) gives 255 parseInt("FF",16) (convert hexadecimal number) gives 255 parseInt("11",16) gives 17 parseInt("eleven") (cannot convert) gives NaN parseInt("$13.50") (cannot convert) gives NaN • parseFloat: convert a string to a floating-point value. Example: parseFloat("10.4") gives 10.4

  21. Summary • Semicolons (;): Manual vs AutomaticInsertion • Location of JavaScript Blocks • <head>..</head>, <body>..</body> • Global variables and functions • Names of Variables and Functions • Global and local variables with the same name • Enclose statements in Braces { and } • Assignment Statements ( =, +=, -=, *=, etc..) • Data Types and operations • Primitive types: • Numbers (whole integers, floating-point values, NaN, Infinity) • Strings • Booleans • null and undefined • Escape Sequences • Conversions between Numbers and Strings • Boolean Values and Operators (>, =, !=, >=, &&, ||, !, ..)

More Related