500 likes | 632 Views
Javascript fundamentals (continue). Example. <script language=javascript> var name="William"; var hometown ="Chico"; function greetme() { var name="Daniel"; document.bgColor="cyan"; document.write("<h2> In function, <em> name </em> is "+name);
E N D
Example <script language=javascript> var name="William"; var hometown ="Chico"; function greetme() { var name="Daniel"; document.bgColor="cyan"; document.write("<h2> In function, <em> name </em> is "+name); document.write(" and <em> hometown </em> is "+hometown); } greetme(); document.write("<h2> Out of the function, <em> name </em> is "+name); document.write(" and <em> hometown </em> is "+hometown); </script> Global variables Local variable
Variable Scope • The “scope” of a variable refers to the context of it’s existence • Two scopes • Global: variable is created outside of a function • Local (private): variable is created inside a function and exists only within the function
Declaring a Variable • Syntax: var <variable name> [= <value> ]; For example: var playerScore; var playerScore = 0;
Naming a Variable • Variable Names (also referred to as Identifiers) must begin with a letter or an underscore and cannot be a reserved word. • Variables are case sensitive and may not contain a space. Example: part_no _part_no part.no +part_no Part_No %Part_No
Declaring a Variable • Variables can be assigned literal data, operations on variables, and logical expressions • var myScore = 100; • var newScore = myScore + yourScore; • var highScore = (myScore > yourScore); • Declaring a variable without giving it a value will cause an “undefined” value to be assigned • var partNumber • partNumber would have a value of “undefined” • Variables cannot be named using reserved words
Declaring a Variable <script language="javascript"> var temperatureYesterday = 100; var temperatureToday = temperatureYesterday; window.alert("Yesterday's Temperature = " + temperatureYesterday); window.alert("Today's Temperature = " + temperatureToday); </script>
Initializing a Variable <script language="javascript"> var firstName; var familyName; var address1; var address2; var city; var state; var zip; var country; var ourCustomer;
Initializing a Variable (continued) function dispVars(){ window.alert("firstName = " + firstName); window.alert("familyName = " + familyName); window.alert("address1 = " + address1); window.alert("address2 = " + address2); window.alert("city = " + city); window.alert("state = " + state); window.alert("zip = " + zip); window.alert("country = " + country); window.alert("ourCustomer = " + ourCustomer); } </script> <body> <input type="button" value="Display Variables" onClick="dispVars();"> </body>
Initializing a Variable with Values <script language="javascript"> var firstName = ""; var familyName = null; var address1 = null; var address2 = null; var city = null; var state =''; var zip = 0; var country ="USA"; var ourCustomer = true;
Changing the Value of a Variable function changeValues(){ firstName = "Elizabeth"; familyName = "Jones"; address1 = "Rose Cottage"; address2 = "25 City Road"; city = "Richmond"; state ='VA'; zip = 23227; country ="USA"; ourCustomer = false; }
Changing the Value of a Variable(continued) <body> <input type="button" value="Display Variables" onClick="dispVars();"> <input type="button" value="Change Variable Values and Display" onClick="changeValues();dispVars()"> </body>
Character Escaping • String Expressions can contain characters that have a special meaning to JavaScript • For example, when using the backslash character in a string it might be misinterpreted unless escaped • var myPath = “C:\MyDocuments\JavaScriptBook” • var myPath = “C:\\MyDocuments\\JavaScriptBook”
Typeof Operator • Returns a string to identify the type of its operand. • Example: var a =1; document.write(“data type of a is “+ typeof(a));
Displaying Variable Values <script type="text/javascript"> var headline1 = "Bank fees increase by 10 percent"; var headline2 = "Mortgage rates at 25 year lows"; var headline3 = "NASDAQ closes above 2000"; document.write("<h1>Breaking news: " + headline1 + "</h1>"); document.write("<h1>Yesterday's news: " + headline2 + "</h1>"); document.write("<h1>Last week's news: " + headline3 + "</h1>"); document.write("<p>News Stories</p>"); document.write("<br><a href=\"" + headline1 + ".html\">" + headline1 + "</a>"); document.write("<br><a href=\"" + headline2 + ".html\">" + headline2 + "</a>"); document.write("<br><a href=\"" + headline3 + ".html\">" + headline3 + "</a>"); </script>
Using Mathematical Operators <script type="text/javascript"> var x = 10; var y = 5; document.write("<br>x + y = " + (x+y)); document.write("<br>x - y = " + (x-y)); document.write("<br>x * y = " + (x*y)); document.write("<br>x / y = " + (x/y)); document.write("<br>x % y = " + (x%y)); document.write("<br> -x = " + (-x)); document.write("<br>--x = " + (--x)); document.write("<br>++x = " + (++x)); </script>
Summary • Variables can store information to be processed • Variable names should be descriptive of what they contain • Variables in JavaScript are not strictly typed • Operators can be used to manipulate the contents of variables • The scope of a variable can be global or private • The keyword var is used to create variables • Variables can be assigned literal data, operations on variables, and logical expressions
Summary (continued) • Declaring a variable without giving it a value will cause an “undefined” value to be assigned • Variables cannot be named using reserved words • Character escaping can be used to include specific characters in text strings that would otherwise be misinterpreted
Lab 3 Step 1:Type or copy & paste the following into your Textpad <html> <head> <title>Untitled Page</title> </head> <body> </body> </html>
Lab 3 Step 2: Insert a script that contains four variables in the head of the document: - the first one contains your name - the second contains a value 0 - the third one is declared but has no value - the fourth one contains an empty string. Step 3: In the body of the document, write another script to display the type of each variable, as well as its value.
Objectives • Use conditional statements, including if and if . . . else • Implement looping statements, including for, for . . . in, while,do . . . while, break, and continue • Know when to use label, switch, and withstatements
If Syntax if(expression){ statement block } Example var numbOfItems = 0; if(numbOfItems > 3){ window.alert(“You have reached the limit.”); }
If Else Syntax if(expression){ statement block } else{ else statement block } Example var numbOfItems = 0; if(numbOfItems > 3){ window.alert(“You have reached the limit.”); } else{ window.alert(“Please choose an Item.”); }
Try / Catch / Finally try { if(answer == 1){ throw "Error1“; } else if(answer == 2){ throw "Error2“; } } catch(er) { if(er == "Error1"){ window.alert(“Invalid Data Type"); } if(er == "Error2"){ window.alert(“Unterminated String”); } } finally( window.alert(“Unknow Error”); }
For Syntax for (starting value; expression; increment/decrement){ statement block } Example for (firstNum = 1; firstNum < 11; firstNum++){ window.alert(firstNum); }
For In Syntax for(variable in array){ statement block } Example var controlStructures = new Array(“For”,”For In”,”While”,”Do While”); for(controlStruc in controlStructures){ document.write(controlStructures[controlStruc]); document.write(“<br>”); }
While Syntax while(expression){ statement block } Example var counter = 1; while(counter <= 10){ document.write(counter); document.write(“<br>”); counter++; }
Do While Syntax do{ statement block } while(expression is true) Example var counter = 1; do( window.alert(counter); counter++; } while(counter <= 10)
Break Example var counter = 1; while(counter > 0){ document.write(counter); i++; if (counter == 5){ break; } } Syntax break;
Continue Syntax continue; Example for(counter = 1; counter <=50; counter++){ if(counter % 2 == 0){ continue; } document.write(counter); document.write(“<br>”); }
Switch Syntax switch(expression){case x: statement block break;case y: statement block break;default: statement block; break;} Example switch(selection){case 0:case 1:case 2: population = 2,688,418; break;case 5: population = 1,711,263; break; }
Using an If Else structure <script type="text/javascript"> function checkIfEligible() { if (document.homeLoanApplication.annualIncome.value<50000) { window.alert("You are not eligible to apply for a home loan."); } else { window.alert("You are eligible to apply for a home loan."); } } </script>
Using an If Else structure <form name="homeLoanApplication"> Annual Income: $ <input type="Text" name="annualIncome"> <input type="submit" value="Check Eligibility" onClick="checkIfEligible();"> </form>
Multiple If Conditions <script type="text/javascript"> function checkIfEligible() { if (document.homeLoanApplication.annualIncome.value<50000||document.homeLoanApplication.liabilities.value>100000) { window.alert("You are not eligible to apply for a home loan."); } else { window.alert("You are eligible to apply for a home loan."); } } </script>
Multiple If Conditions (continued) <form name="homeLoanApplication"> Annual Income: $ <input type="Text" name="annualIncome"> Current Liabilities: $ <input type="Text" name="liabilities"> <input type="Submit" value="Submit" onClick="checkIfEligible()"> </form>
Using a While Loop <script type=“text/javascript”> function printPayments() { var principal=document.homeLoanCalculator.principal.value; var years=document.homeLoanCalculator.years.value; var annualPayment=principal/years; var y=1; document.write("<table border=\"1\" width=\"100%\">"); document.write("<tr>"); document.write("<td>Year</td>"); document.write("<td>Value</td>"); document.write("</tr>");
Using a While Loop (continued) while (years>0) { document.write("<tr>"); document.write("<td>"+y+"</td>"); document.write("<td>$"+principal+"</td>"); document.write("</tr>"); principal-=annualPayment; y++; years--; } document.write("</table>"); } </script>
Using while loop <form name="homeLoanCalculator"> Outstanding Principal: $<input type="Text" name="principal"> Years to Pay: <input type="Text" name="years"> <input type="Submit" value="Submit" onClick="printPayments();">
Using For <script type=“text/javascript”> function printPayments() { var principal=document.homeLoanCalculator.principal.value; var years=document.homeLoanCalculator.years.value; var annualPayment=principal/years; var y=1; document.write("<table border=\"1\" width=\"100%\">"); document.write("<tr>"); document.write("<td>Year</td>"); document.write("<td>Value</td>"); document.write("</tr>");
Using For (continued) for (i=0; i<years; i++) { document.write("<tr>"); document.write("<td>"+y+"</td>"); document.write("<td>$"+principal+"</td>"); document.write("</tr>"); principal-=annualPayment; y++; } document.write("</table>"); } </script>
Using For (continued) <form name="homeLoanCalculator"> Outstanding Principal: $<input type="Text" name="principal"> Years to Pay: <input type="Text" name="years"> <input type="Submit" value="Submit" onClick="printPayments();"> </form> </body> </html>
Using a Switch Construct <HTML> <HTEAD> <SCRIPT language=javascript> var selobj = ""; function displaypopulation(selobj){ var population = 0; switch(selobj.selectedIndex){ case 0: population = "2,688,418"; break; case 1: population = "2,926,324"; break; case 2: population = "2,233,169"; break; case 3: population = "1,711,263"; break; } alert("Population of " + selobj.options[selobj.selectedIndex].value + " = " + population); } </SCRIPT>
Using a Switch Construct (continued) </HEAD> <BODY onload=document.switchdoc.switchlist.focus();> <FORM name=switchdoc> <TABLE border=0> <TR> <TD vAlign=top>Display Population For: <SELECT onchange=“displaypopulation(this);” name=switchlist> <OPTION value=Kansas selected>Kansas <OPTION value=Iowa>Iowa <OPTION value=Utah>Utah <OPTION value=Nebraska>Nebraska </SELECT> <br><i>Census 2000</i> </TD> </TR> </TABLE> </FORM> </BO> </HTML>
Summary • Using control structures allows your code to change the flow • Using this control brings more sophistication and power to your scripts • Using conditions and loops controls when certain blocks of code are executed • Loops can be predetermined or controlled by logic built into them • If Else control structures account for one of two possible choices
Summary (continued) • Switch control structures allow for one of many possible code executions • Endless loops can be created by not incrementing or decrementing a counter variable or using a condition that never evaluates to false • While loops may not iterate at all – the expression is evaluated before the loop executes • Do While loops iterate at least once – the expression is not evaluated until the bottom of the structure
Lab Step 1:Cut& paste this code <html > <head> <title>Untitled Page</title> <!– Insert your script here --> </head> <body> </body> </html>
Lab Step 2: In the body of the HTML page, Create a HTML form that allows a user to enter the current points (integer), looks like the following:
Lab Step 3: Create a script that does the following: • If the current point is greater than 90, prompt “ You earn an A” • If the current point is less than 90 but greater than 80, prompt “ You earn a B” • Otherwise, prompt “You need to work harder”