CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

36
CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures

Transcript of CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

Page 1: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

CNIT 133 Interactive Web Pags –JavaScript and AJAX

Control Structures

Page 2: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

Agenda• My Web Site: http://fog.ccsf.edu/~hyip (download syllabus, class notes).• Control Structures• If statements (if/else statement)• Switch statement• For statement (for/in statement)• While statement (do/while statement)• Label statement• Break statement• Continue statement• Throw statement• Try/catch/finally statement• Empty statement

Page 3: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

Control Structures

• Control structures let the programmer controls the flow of the program make the programs capable of reacting dynamically to a variety of conditions.

Page 4: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

Making decisions with the if control structure

• An if statement tells your script to perform an action or set of actions only if a particular condition is true.

• “if” statement has two forms, the first form is (no else clause):if (condition)

statement; (condition) is evaluated. If the resulting value is true, statement is executed. If false, statement

is not executed.

Or you can always replace a single statement with a statement block.if (condition) {

statements;}

• NOTE: if there is only one statement, you can omit the braces.

Page 5: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

if statement sample<html><head><title>if control</title></head><body><h1>Control Structure</h1><script language="JavaScript" type="text/javascript">var response = parseInt(prompt("What is 100 + 50?", "");if (response == 150) {

alert("That is correct! 100 + 50 = 150");}</script></body></html>

Page 6: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

Providing a default action with else

• The second form of the if statement introduces an else clause that it executed when condition is false:

if (condition) {statements

} else {default statements

} (condition) is evaluated. If it is true, “statements” is executed;

otherwise, “default statements” is executed.

Page 7: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

if else statement sample<html><head><title>if else control</title></head><body><h1>if else Control Structure</h1><script language="JavaScript" type="text/javascript"> var response = parseInt(prompt("What is 100 + 50?", "");if (response == 150) {

alert("That is correct! 100 + 50 = 150");} else { alert("Wrong! 100 + 50 = 150");}</script></body></html>

Page 8: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

else if statement• “else if” is not really a JavaScript statement, but simply a frequently used

programming idiom that results when repeated if/else statements are used:if (condition) {

statements} else if (condition2) {

statements} else if (condition3) {

statements..} else if (conditionN) {

statements} else {

default statements}

Page 9: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

else if statement sample<html><head><title>else if control</title></head><body><h1>else if Control Structure</h1><script language="JavaScript" type="text/javascript">var response = prompt("Enter a color:", "red");if (response == "red") {

alert("It is RED");} else if (response == "blue") { alert("It is BLUE");} else if (response == "white") { alert("It is WHITE");} else { alert("Not Red, Blue, White");}</script></body></html>

Page 10: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The switch statement• When a switch executes, it computes the value of expression and then

looks for a case label that matches that value. If it finds one, it starts executing the block of code at the first statement following the case label. If it does not find a case label with a matching value, it starts execution at the first statement following a special default: label. Or, if there is no default: label, it skips the block of code all together.

switch (expression) {case label1:

statements; break;

case label2: statements; break;

default: statements;

}

Page 11: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

switch statement sample<html><head><title>switch control</title></head><body><h1>switch Control Structure</h1><script language="JavaScript" type="text/javascript">var response = prompt("Enter a color:", "red");switch (response) {Case "red": alert("It is RED"); break;case "blue": alert("It is BLUE"); break;Case "white": alert("It is WHITE"); break;default: alert("It is not RED, Blue or WHITE");}</script></body></html>

Page 12: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The for Loop

• The for loop is the perfect tool when you know how many times you need to perform a particular set of actions.

for (initial expression; condition; update expression) {statements;

}

for (var i=1; i <= 3; i++) {document.write("i is: ", i);

}

Page 13: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The for Loop sample<html><head><title>for loop</title></head><body><h1>for Loop control structure</h1><script language="JavaScript" type="text/javascript">var favMovie = "";document.write("<h1>Your Favorite Movies</h1>");for (var i = 1; I <= 3; i++) {

favMovie = prompt("Enter your #" + i + " favorite movie:", "");document.write(i, ". ", favMovie, "<br>");}</script></body></html>

Page 14: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The for/in Loop (Advanced topic)• The for/in statement provides a way to loop through the

properties of an object.for (variable in object) {

statements;}

• The body of the loop is executed once for each property of object. Before the body of the loop is executed, the name of one of the object’s properties is assigned to variable as a string. Within the body of the loop, you can use this variable to look up the value of the object’s property with the [] operator:

for (var prop in my_object) {document.write("Prop name: " + prop + " ; value: " +

my_object[prop], "<br>");}

Page 15: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The for/in Loop (Advanced topic)• You can copy the name of all object properties into an array:

var obj = { x:1, y:2, z:3 }; var my_array = new Array();

var i = 0;for (my_array[i++] in obj) {

/* empty loop body */ ;}

• JS arrays are special kind of object:for (i in my_array) {

alert(i); // index of array will be display, 0 to 2}

Page 16: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The for/in Loop sample<html><head><title>for in loop</title></head><body><h1>for in Loop control structure</h1><script language="JavaScript" type="text/javascript">var obj = {x:1, y:2, z:3};var my_array = new Array(); /* create a new array */var i = 0;

for (i in obj) { document.write(i, "<br />"); // output x, y, z

}i = 0;for (my_array[i++] in obj) {

/* empty loop body - copy property name to an array */ ;}document.write(my_array, "<br />"); // output x, y, z

i = 0;for (i in my_array) {

document.write(i , "<br />"); // output 0, 1, 2 }</script></body></html>

Page 17: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The while Loop

• The while statement works by evaluating “expression”. If it is false, JavaScript moves on to the next statement after while statement in the program. If it is true, the “statements” that forms the body of the loop is executed, and “expression” is evaluated again. The cycle continues until “expression” evaluates to false:

while (expression) {statements;

}

Page 18: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The while Loop sample<html><head><title>while loop</title></head><body><script language="JavaScript" type="text/javascript">var num = parseFloat(prompt("Enter a number:", ""));while ( isNaN(num)) {

alert("Error! You did not enter a number! ");num = parseFloat(prompt("Enter a number:", ""));

}alert("Success! You entered: " + num);</script></body></html>

Page 19: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The do/while Loop• The do/while loop is much like a while loop, except that the

loop expression is tested at the bottom of the loop rather than at the top. This means that the body of the loop is always executed at least once:

do {statements;

} while (expression)

• The do/while loop is less commonly used than its while cousin. It is somewhat uncommon to encounter a situation in which you are always sure that you want a loop to execute at least once.

Page 20: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The do/while Loop sample<html><head><title>do…while loop</title></head><body><h1>do…while loop control structure</h1><script language="JavaScript" type="text/javascript">var num = 0;do {

num = parseFloat(prompt("Enter a number:", ""));if ( isNaN(num) ) {

alert("Error! You did not enter a number! ");}

} while ( isNaN(num) )alert("Success! You entered: " + num);</script></body></html>

Page 21: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

label• The “case:” and “default:” labels used with the switch statement are a

special case of a more general label statement. Any statement may be labeled by preceding it with an identifier name and a colon:

identifier: statement;

• The identifier can be any legal JS identifier that is not a reserved word.parser:for (i =0; i < 5; i++) {

/* JS code */}

• By labeling a statement, you give it a name that you can use to refer to it elsewhere in your program. You can label any statement, although the only statements that are commonly labeled are loops – while, do/while, for and for/in. By giving a loop a name, you can use break and continue to exit the loop or to exit a single iteration of the loop.

Page 22: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The break statement• The break statement causes the innermost enclosing loop or a switch

statement to exit immediately:break;

• Sometimes a loop is used to perform a task like searching for a desired string. Once the desired item is found, there is no need to continue looping. “break” statement provides a way for us to break out of such a loop when our task is accomplished.

var i;var a = ["ABC", "xyz", "target", "Bbc", "ccd"];for (i = 0; i < a.length; i++) {

if (a[i] == "target") {alert("Found it");break;

}}

Page 23: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The break statement sample<html><head><title>break statement</title></head><body><h1>break statement</h1><script language="JavaScript" type="text/javascript">var favMovie = "";var moreMovie = "";document.write("<h1>Your Favorite Movies</h1>");for (var i = 1; i<=3; i++) {

favMovie = prompt("Enter your #" + i + " favorite movie:", "");document.write(i, ". ", favMovie, "<br>");moreMovie = prompt("More movie? ", "yes");if (moreMovie == "yes") {

;} else {

break;}

}</script></body></html>

Page 24: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The break statement with label• JavaScript allows the break keyword to be followed by the name of a

label:break label_name;

When break is used with a label, it jumps to the end of, or terminates, the named statement, which may be any enclosing statement.

As discussed before, a newline is not allowed between the break keyword and the lebel_name.

Also, there should not be any other statement in between a label name and associated loop.

Page 25: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The break statement with label sample

<html><head><title>break with label</title></head><body><h1>break statement with label</h1><script language="JavaScript" type="text/javascript">

document.write("Entering the loop!<br /> ");outerloop: // This is the label namefor (var i = 0; i < 5; i++) {

document.write("Outerloop: " + i + "<br />");innerloop:for (var j = 0; j < 5; j++) {

if (j > 3 ) break; // Quit the innermost loopif (i == 2) break innerloop; // Quit the inner loopif (i == 4) break outerloop; // Quit the outer loopdocument.write("&nbsp;&nbsp;&nbsp;Innerloop: " + j + " <br />");

}}document.write("Exiting the loop!<br /> ");

</script></body></html>

Page 26: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The continue statement• The continue statement is similar to the break statement. Instead of exiting a loop,

however, continue restarts a loop in a new iteration:continue;

• The continue statement, in both its labeled and unlabeled forms, can be used only within the body of a while, do/while, for, or for/in loop. Using it anywhere else causes a syntax error.

• When the continue statement is executed, the current iteration of the enclosing loop is terminated, and the next iteration begins: In a while loop, the specified expression at the beginning of the loop is tested

again. If it is true, the loop body is executed starting from the top. In a do/while loop, execution skips to the bottom of the loop, where the loop

condition is tested again before restarting the loop at the top. In a for loop, the increment expression is evaluated, and the test expression is

tested again to determine if another iteration should be done. In a for/in loop, the loop starts over with the next property name being

assigned to the specified variable.

Page 27: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The continue statement sample<html><head><title>continue statement</title></head><body><h1>continue statement control structure</h1><script language="JavaScript" type="text/javascript">var favMovie = "";document.write("<h1>Your Favorite Movies</h1>");for (i = 1; i<=3; i++) {favMovie = prompt("Enter your #" + i + " favorite movie:", "");if (favMovie == "abc") {

alert("Skip this movie");continue;

} document.write(i, ". ", favMovie, "<br>");}</script></body></html>

Page 28: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The continue statement with label• The continue statement can also be used with a

label:continue label_name;

• Line breaks are not allowed between the continue statement and its labe_lname.

• Also, there should not be any other statement in between a label name and associated loop.

Page 29: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The continue statement with label sample

<html><head><title>continue with label</title></head><body><h1>continue statement with label</h1><script language="JavaScript" type="text/javascript">

document.write("Entering the loop!<br /> ");outerloop: // This is the label namefor (var i = 0; i < 3; i++) {

document.write("Outerloop: " + i + "<br />");for (var j = 0; j < 5; j++) {

if (j == 3){continue outerloop;

}document.write("&nbsp;&nbsp;&nbsp;Innerloop: " + j + "<br />");

} }

document.write("Exiting the loop!<br /> ");</script></body></html>

Page 30: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The throw statement• An exception is a signal that indicates that some sort of exceptional

condition or error has occurred.• To throw an exception is to signal an error or exceptional condition.• To catch an exception is to handle it – to take whatever actions are

necessary or appropriate to recover from the exception.• In JavaScript, exceptions are thrown whenever a runtime error occurs and

whenever the program explicitly throws one using the throw statement.• Exceptions are caught with the try/catch/finally statement.• The throw syntax:

throw expression;

Expression may evaluate to a value of any type. Commonly, it is an Error object or an instance of one of the subclasses of Error. It can also be useful to throw a string that contains an error message, or a numeric value that represent some sort of error code.

The expression can be a string, integer, Boolean or an object.

Page 31: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The throw statement (continue…)• When an exception is thrown, the JavaScript interpreter immediately

stops normal program execution and jumps to the nearest exception handler.

• Exception handlers are written using the catch clause of the try/catch/finally statement.

• If the block of code in which the exception was thrown does not have an associated catch clause, the interpreter checks the next highest enclosing block of code to see if it has an exception handler associated with it.

• This continues until a handler is found. If no exception handler is ever found, the exception is treated as an error and is reported to the user.

• The throw statement is standardized by ECMAScript v3 and implemented in JavaScript 1.4.

• The Error class and its subclasses are also part of ECMAScript v3, but they were not implemented until JavaScript 1.5.

Page 32: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The try/catch/finally statement• The try/catch/finally statement is JavaScript’s exception-

handling mechanism. • The try clause of this statement simply defines the block of code

whose exceptions are to be handled. • The try block is followed by a catch clause, which is a block of

statements that invoked when an exception occurs anywhere within the try block.

• The catch clause is followed by a finally block containing cleanup code that is guaranteed to be executed, regardless of what happens in the try block.

• Both the catch and finally blocks are optional, but a try block must be accompanied by at least one of these blocks.

• The try, catch, and finally blocks all begin and end with curly braces. These braces are a required part of the syntax and cannot be omitted.

Page 33: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The try/catch/finally statement (continue…)

• try/catch/finally syntax:try {

// this code runs from the top of the block // to the bottom without problems. But it can

// sometimes throw an exception, either directly, with // a throw statement, or indirectly, by calling a method // that throws an exception.}catch (e) {

// the statements in this block are executed if, and only // if, the try block throws an exception. These statements can // use the local variable e to refer to the Error object or other // value that was thrown.

}finally {

// this block contains statements that are always executed. They are // executed whether the try block terminates: // 1) normally, after reaching the bottom of the block // 2) because of a break, continue, or return statement // 3) with an exception that is handled by a catch clause // 4) with an uncaught exception that is still propagating

}

Page 34: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The try/catch/finally statement with Error object sample

<script language="JavaScript" type="text/javascript">function factorial(x) {

if (x < 0) { //input invalid, thro exceptionthrow new Error("x must not be negative");/* Error text will store in the Error.description and Error.message */

}for (var f=1; x > 1; f *= x, x--) {

; //f(0) and f(1) are equal to 1}return f;

}</script><script language="JavaScript" type="text/javascript">try {

document.write("factorial of 3 is: ", factorial(3), "<br />");document.write("factorial of -2 is: ", factorial(-2), "<br />");

}catch (err) {

/* IE has Error.description; ECMA don't has Error.descriptionboth IE and ECMA have Error.message where the text will be stored.both IE and ECMA have Error.nameboth IE and ECMA have Error.number */

document.write("Description: ", err.description);document.write("<br />message: ", err.message);document.write("<br />name: ", err.name);document.write("<br />number: ", err.number);

}finally {

document.write("<br />End of Try/Catch/Finally");}</script>

Page 35: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The try/catch/finally statement sample

var x=prompt("Enter a number between 0 and 10:","");try {

if(x>10) { throw "Err1"; // pass a string to the catch clause

} else if(x<0) {throw "Err2";

}} catch(er) {

if(er=="Err1") alert("Error! The value is too high");

if(er == "Err2") alert("Error! The value is too low");

}finally {alert("the number you entered: " + x);}

Page 36: CNIT 133 Interactive Web Pags – JavaScript and AJAX Control Structures.

The empty statment

• The empty statement:;

• Executing the empty statement has no effect and performs no action.

• Initialize an array a:for (i = 0; i < a.length; a[i++] = 0) ;

• When you intentionally use the empty statement, it is a good idea to comment your code in a way that makes it clear that you are doing it on purpose:

for (i = 0; i < a.length; a[i++] = 0) /* empty */ ;