introduction to computer programming 4. program structure iii - 1helena program structure iii...
DESCRIPTION
Introduction to Computer Programming 4. Program Structure III - 3http://www.cs.cityu.edu.hk/~helena Location of JavaScript Blocks Demo.. … … … There can be more than 1 JavaScript blocks. JavaScript blocks can be in :, and But we usually put most in. (See below) 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... Reasons: (1)The browser loads everything in the tag before it starts executing any JavaScript. That means, if we put global variables and functions in, then they can be used immediately when the page begins to load. (2)Easier to lookup.TRANSCRIPT
Introduction to Computer Programming 4. Program Structure III - 1http://www.cs.cityu.edu.hk/~helena
Program Structure IIIProgram Structure III
[Please switch off your phone]
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
Introduction to Computer Programming 4. Program Structure III - 2http://www.cs.cityu.edu.hk/~helena
The mystery of Semicolons (;)• Semicolons (;) are used to separate statements from each other.
• 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 HOT questions at the course web)
a = 3b = 4alert(a+b)
a = 3;b = 4;alert(a+b);
//calculate average of marks:var a = ( parseInt(document.F1.CMark.value) +
parseInt(document.F1.EMark.value) +parseInt(document.F1.MMark.value))
/ 3alert(a)
• The fact: JavaScript automatically inserts semicolons if the line seems to be complete.
a = 3b = 4
a = 3 b = 4 a = 3; b = 4;
//calculate average of marks:var a = ( parseInt(document.F1.CMark.value) +
parseInt(document.F1.EMark.value) +parseInt(document.F1.MMark.value))
/ 3;alert(a);
• Can be omitted if each statement is on a separate line.But not suggested to omit!!
Example: a = 3;b = 4;
The invisible semicolons are automatically inserted.
Introduction to Computer Programming 4. Program Structure III - 3http://www.cs.cityu.edu.hk/~helena
Location of JavaScript Blocks<html><head> <title>Demo</title>
</head><body>..................................</body></html>
<script type="text/javascript">……</script>
<script type="text/javascript">……</script>
<script type="text/javascript">……</script>
• There can be more than 1 JavaScript blocks.
• JavaScript blocks can be in :<head> </head>, and <body> </body>
But we usually put most in <head></head>. (See below)
• 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>.Reasons:
(1) 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.
Introduction to Computer Programming 4. Program Structure III - 4http://www.cs.cityu.edu.hk/~helena
Names of Variables and FunctionsRecall / Summarize:
• JavaScript is case-sensitive.Example: the if keyword must not be typed as If.
• CAN consist of any letter, digit, and underscore (_).
• CANNOT start with a digit. Example: 9To5 is NOT valid.
• CANNOT be a JavaScript keyword. Examples: break do function null typeofcase else if return varcontinue export import switch voiddefault false in this whiledelete for new true with
• Should be descriptive. Bad examples: Function1, temp These names can’t tell what the functions do.
• 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
keywords, variables, function names
camelCase
Introduction to Computer Programming 4. Program Structure III - 5http://www.cs.cityu.edu.hk/~helena
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 type="text/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 type="text/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 global variable – eg. previous “Counter” example We should use global variables ONLY WHEN really necessary and appropriate.
Use local variable(Preferred!!) – we often use a variable only within the function and we do not need to keep it after the function stops.*
* “return result;” actually meansTo pass back the value of the variable result, NOT to pass back the variable result.
ie. the variable result is no longer required after “return result;”.
Actually happens very often
Introduction to Computer Programming 4. Program Structure III - 6http://www.cs.cityu.edu.hk/~helena
Names of Variables and Functions
? What happens if a local and a global variables have the same name..
<html><head>
<title>Demo</title><script type="text/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>
To avoid confusion, we usually DON'T use the same name for local and global variables.
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.
Suppose wecall f1 and then alert theglobal x:
Call f1()Just alert it
undefined
In f1, x is 3
Introduction to Computer Programming 4. Program Structure III - 7http://www.cs.cityu.edu.hk/~helena
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!');}
Passed.
Correct
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!');
What is your mark?
80
Passed.You must take this course again!
Wrong outputAlthough last 3 lines are aligned at the same column,JavaScript does not know that they are 'together'.(Indentations, ie. spacing at the beginning of each line, are meaningless to the
browser.)
In such case we add { and } to group them together (known as compound statement):
Introduction to Computer Programming 4. Program Structure III - 8http://www.cs.cityu.edu.hk/~helena
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”
Introduction to Computer Programming 4. Program Structure III - 9http://www.cs.cityu.edu.hk/~helena
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;
Right-hand-side Left-hand-side
• We can also assign a value at the same time when a variable is declared:Example: var x=4, msg="How are you?";
• More powerful assignment operators.
Example: salary += 100; salary = salary + 100; are the same.
counter += 1; counter=counter+1; are the same.
Similar ones are : -=, *=, /=, %=
Introduction to Computer Programming 4. Program Structure III - 10http://www.cs.cityu.edu.hk/~helena
• Data Types: the types 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.
Data Types
See week 3 tutorial
Introduction to Computer Programming 4. Program Structure III - 11http://www.cs.cityu.edu.hk/~helena
Data Types
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; and counter += 1;
count--; is the same as count = count - 1; and counter -= 1;
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); - display 83 !!
Introduction to Computer Programming 4. Program Structure III - 12http://www.cs.cityu.edu.hk/~helena
Data TypesBooleans• 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:
Sample JavaScript condition Meaning of JavaScript condition
Equality operatorsx == y x is equal to y
x != y x is not equal to y
Relational operatorsx > y x is greater than yx < y x is less than y
x >= y x is greater than or equal to yx <= y x is less than or equal to y
a Boolean value can only be true or false
The results could only be true / false (Boolean values)
Introduction to Computer Programming 4. Program Structure III - 13http://www.cs.cityu.edu.hk/~helena
Data TypesUse 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.');
2 other styles:
if (all_passed!=false)
alert('Congradulations!...');
Each if (..) actually checks a Boolean value.
true or false
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.
A bit complicated (Not preferred)
if (all_passed)
alert('Congradulations!...');
Simple and nice
Introduction to Computer Programming 4. Program Structure III - 14http://www.cs.cityu.edu.hk/~helena
Data Types
Decision Making: Logical OperatorsTo perform Boolean algebra.Logical AND : &&Logical OR : ||Logical NOT : !
if ( (english_mark >= 81) && (chinese_mark >= 81) &&
(maths_mark >= 81) )alert('Well done! All
distinctions!');
if ( side1 == side2 && side2==side3)
alert('Equilateral triangle');side1 side2side3
Don’t write if (side1 == side2 == side3)
* Try adding it to the "MARKS TO GRADES CONVERSION" example (replace english_mark with document.F1.EMark.value etc..)
Checking of Equilateral Triangle:
Introduction to Computer Programming 4. Program Structure III - 15http://www.cs.cityu.edu.hk/~helena
Data Types
Decision Making: Logical Operators
To perform Boolean algebra.Logical AND : &&Logical OR : ||Logical NOT : !
var all_passed = true;if ( (english_mark < 46) ||
(chinese_mark < 46) ||(maths_mark < 46) )all_passed = false;
if (all_passed)alert('Congradulations! You pass all
subjects.');else
alert('Sorry! You cannot pass all subjects.');
if ( ! all_passed)alert('Sorry! You ..');
elsealert('Congradulations! ..');
Same as:
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.
Introduction to Computer Programming 4. Program Structure III - 16http://www.cs.cityu.edu.hk/~helena
Data Types
She said: "I don't understand!"
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:
Introduction to Computer Programming 4. Program Structure III - 17http://www.cs.cityu.edu.hk/~helena
Data Types
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).
She said: "I don't understand!"
Strings
• Question: how to display this string:
Another approach (Escape Sequence) – see next page.
Introduction to Computer Programming 4. Program Structure III - 18http://www.cs.cityu.edu.hk/~helena
Data TypesEscape SequencesA method to represent special characters by combining backslash (\) with another character:
Escape sequence Description\n new line\t tab\\ backslash\" Double quote\' Single quote
Example: alert( 'I\'m Happy!');
' 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.
“Escape away” from normal
interpretation.-- to produce special effect
Introduction to Computer Programming 4. Program Structure III - 19http://www.cs.cityu.edu.hk/~helena
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 (rounded).Example: var x=5/3;
x.toFixed( )gives 2x.toFixed(1) gives 1.7x.toFixed(2) gives 1.67
Data Types
Introduction to Computer Programming 4. Program Structure III - 20http://www.cs.cityu.edu.hk/~helena
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 255parseInt("FF",16) (convert hexadecimal number) gives 255parseInt("11",16) gives 17parseInt("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
Data Types
parseInt is for integers, so contents since “.14..” are ignored.
Introduction to Computer Programming 4. Program Structure III - 21http://www.cs.cityu.edu.hk/~helena
Summary
Semicolons (;): Manual vs Automatic Insertion
Location of JavaScript Blocks<head>..</head>, <body>..</body>Global variables and functions
Names of Variables and FunctionsGlobal and local variables with the same name
Enclose statements in Braces { and }
Assignment Statements ( =, +=, -=, *=, etc..)
Data Types and operationsPrimitive types:
Numbers (whole integers, floating-point values, NaN, Infinity)StringsBooleans
null and undefinedEscape SequencesConversions between Numbers and StringsBoolean Values and Operators (>, =, !=, >=, &&, ||, !, ..)