21
(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena 4. Program Structure III - 1 http://www.cs.cityu.edu.hk/~helena Program Structure III Program 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

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 4. Program Structure III - 1 helena

  • View
    225

  • Download
    0

Embed Size (px)

Citation preview

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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 Helpdesk’s 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.

Example: a = 3;b = 4;

The invisible semicolons are automatically inserted.

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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 LANGUAGE=javascript>…

…</SCRIPT>

<SCRIPT LANGUAGE=javascript>…

…</SCRIPT>

<SCRIPT LANGUAGE=javascript>…

…</SCRIPT>

• 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:

(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.

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 4. Program Structure III - 4http://www.cs.cityu.edu.hk/~helena

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 typeofcase else if return varcontinue export import switch voiddefault false in this whiledelete 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

keywords, variables, function names

camelCase

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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 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

To 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

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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 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>

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.

Call f1()

Just alert it

undefined

In f1, x is 3

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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'.

In such case we add { and } to group them together:

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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”

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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

• Assign a value at the same time when 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 : -=, *=, /=, %=

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 4. Program Structure III - 10http://www.cs.cityu.edu.hk/~helena

• 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.

Data Types

See week 3 tutorial

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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); not 123(10)!! [123 is 1*100 + 2*10+3]

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 4. Program Structure III - 12http://www.cs.cityu.edu.hk/~helena

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:

Sample JavaScript condition Meaning 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

a Boolean value can only be true or false

The results could only be

true / false (Boolean values)

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 4. Program Structure III - 13http://www.cs.cityu.edu.hk/~helena

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.');

May simply write :

if (all_passed)

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.

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 4. Program Structure III - 14http://www.cs.cityu.edu.hk/~helena

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!');

if ( side1 == side2 && side2==side3)

alert('Equilateral triangle');side1 side2

side3Don’t write if (side1 == side2 == side3)

* Try adding it to the "MARKS TO GRADE CONVERSION" example (replace english_mark with document.F1.EMark.value etc..)

Checking of Equilateral Triangle:

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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==false)alert('Sorry! You cannot pass all

subjects.');

May also be simplified as:if ( ! all_passed)

alert('Sorry! You cannot...');

if (all_passed != true)alert('Sorry! You cannot...');

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.

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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:

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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:

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 4. Program Structure III - 18http://www.cs.cityu.edu.hk/~helena

Data Types

Escape 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

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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.

Example: var x=5/3;

x.toFixed( )gives 2

x.toFixed(1) gives 1.7

x.toFixed(2) gives 1.67

Data Types

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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 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

Data Types

(CS1301) Introduction to Computer Programming City Univ of HK / Dept of CS / Helena Wong 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 (>, =, !=, >=, &&, ||, !, ..)