IT 130 – Internet and the Web - Yosef Mendelsohn - PowerPoint PPT Presentation

it 130 internet and the web yosef mendelsohn n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
IT 130 – Internet and the Web - Yosef Mendelsohn PowerPoint Presentation
Download Presentation
IT 130 – Internet and the Web - Yosef Mendelsohn

play fullscreen
1 / 76
IT 130 – Internet and the Web - Yosef Mendelsohn
122 Views
Download Presentation
elia
Download Presentation

IT 130 – Internet and the Web - Yosef Mendelsohn

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. IT 130 – Internet and the Web- Yosef Mendelsohn JavaScript contd: Scope, Built-in functions, Precedence, If-statements

  2. Fair Warning: • Several of the concepts from the next two Javascript lectures will be well-covered on your final exam. • You can expect at least one question on each of: • scope • built-in functions in general • parseInt() function • precedence • if-else will be extensively covered between now and the end of the course. 2

  3. New topic: Built-In Functions • In addition to the functions we have been creating ourselves, JS has many built-in functions. Some of them are quite useful. • In fact, document.write() is one such built-in function. It takes whatever the programmer puts inside the parentheses and outputs the result to an HTML document. • Another convenient JS function is alert() . This works similarly to a document.write function, except that the output goes to a dialog box instead of an HTML page.

  4. Some Predefined Functions We have already created many functions. However the JS language has many built-in functions that we can use. document.write() alert() Math.sqrt() Math.floor() Date() parseInt() prompt() //use ONLY during testing 4

  5. Some of these predefined functions in use: var number, rollDice, todaysDate; number = Math.sqrt(25); rollDice = (Math.random()*6) +1; //Generates a random number between 1 and 6 //More on this later todaysDate = Date(); //generates the date and time based //on the computer’s clock alert("The date is:" + todaysDate); 5

  6. The alert()function • A built-in JS function • Works similarly to the document.write function, except that the output goes to a dialog box instead of an HTML page. • Because the output does not write to an HTML page, you can NOT use HTML markup. • I.e. Only text can be outputted to an alert dialog box. • The most common usage of the alert() box is to give the user an error message such as entering incorrect information in a form. • e.g. alert(“You must enter your birthdate as MMDDYY”); • It is VERY convenient for testing purposes. • Rather than have to write out an entire document.write statement, you can simply output a quick ‘alert’ function

  7. The alert() function in action: <script type=“text/javascript"> var age=30; alert("You are" + age + " years old."); </script> Will display the following alert box:

  8. The alert() function alert("testing an alert box"); var x=5; alert(x); var age=30; alert("You are " + age + " years old."); • A “quick and easy” way of outputting information – particularly useful for testing purposes.

  9. Quick review: the + operator • Recall how the ‘+’ operator works differently depending on the data types: • "foo" + "bar"  • "foobar“ (two strings, therefore, concatenation) • "5" + "6"  • "56“ (also two strings, therefore, concatenation) • 5 + 6  • 11 (two numbers, therefore addition) • What about the following? • "5" + 6  • "56" • 6 + "foo"  • "6foo“ • In other words, if you try to add a string to anything including numbers, the ultimate result will be a string.

  10. ** Built-in functions contd:parseInt() • Recall that when you retrieve the value from a textbox, the value is considered to be a “string” of TEXT. That is, the value is NOT a number. • Consider the following: var age = document.form1.txtAge.value; //eg: 25 var ageNextYear = age+1; • The value of ageNextYear will be set to 251 !!! • The reason for this strange behavior is that the ‘+’ operator is placed between TEXT (“25”) and an INTEGER (1). In this case, you do NOT get addition! You get concatenation.

  11. ** Key Point: • Whenever you read in a value from a form and wish that value to be treated as a NUMBER, you should invoke the (highly useful) built-in JS function called: parseInt() • Here is one way of doing that: var age = document.form1.txtAge.value; age = parseInt(age); //age can now be treated as a regular number • Note that parseInt() will work ONLY if the value from the form contains nothing other than DIGITS. • One period is okay too. • If there are any other characters such as commas, quotes, letters, symbols, etc, this will likely cause your script to malfunction. • FROM NOW ON, whenever you read in a quantity from your web form, you MUST invoke the parseInt() function on that number. • The grader will deduct points every time you forget to do so! 

  12. *** The Math.random()function: • The following line of code: (Math.random()*25) +1; Will generate a random number between 1 and 25 • You can replace the number 25 with any other number you like • Will give back a numeric value with integers. The parseInt function below will remove (“truncate”) all of the numbers after the decimal. E.g. 23.88724 will be converted to just 23. • You will use this function many times between now and the end of the quarter. • Math.random and parseInt in action: var random = (Math.random()*10)+1; random = parseInt(random); //remove the decimal numbers (later) alert("A random number between 1 and 10: “ + random);

  13. * Another use for parseInt() • parseInt() also is useful for removing decimal values • Recall that Math.random() returns a number that has decimal spaces. Frequently, however, we simply want an integer. We can use parseInt() to remove the decimals: var random = (Math.random()*10)+1; random = parseInt(random); //remove the decimal numbers alert("A random number between 1 and 10: “ + random);

  14. ** Built-in functions contd:parseFloat() • Recall that parseInt chops off all decimal values. • If you want to KEEP decimals, you must use parseFloat() var length = document.form1.txtLength.value; //eg: 134.73 length = parseFloat(length);

  15. ** Using parseInt and parseFloat • From now on you MUST use parseInt() or parseFloat() – but ONLY where appropriate. • Whenever reading in a numeric quantity from a form (e.g. age, weight, amount, etc), use them. • If you are not reading in a quantity (e.g. a name, city, etc), do NOT use them.

  16. Scope 16 The scope of a variable is the part of the program where the variable can be used / accessed / referenced. There are two types of variables: local and global.

  17. Scope 17 • A local variable is declared in a function. Its scope is within the function where it is declared. In other words, it can be used only within that function. • A global variable is used between script tags in the body of the web page. Its scope is within the entire web page. • In other words, it can be used throughout the entire current document (although, only inside Javascripts). • However, global variables can be problematic at time, and are RARELY EVER USED!! • In fact, we will NOT be using global variables in this course.

  18. Local Variables • All variables declared in a function are local variables: they do not exist outside that function. • Although local variables may seem restricted, they are very useful and are used constantly in programming. 18

  19. Scope contd • What is the scope of ‘x’ in this code? <script> function f1() { var x; x = 3; document.write(x); } <script> • Answer: the function ‘f1’

  20. Scope contd • Are there any problems with this code? <script> function f1() { var x; x = 3; document.write(x); } function f2() { x=5; } </script> • Answer: the variable ‘x’ inside function ‘f2’ is undeclared. • ‘f2’ has no idea that the variable x exists elsewhere.

  21. Where should you put your variables? • It’s okay to have variables anywhere, but remember, you can not use a variable until you declare it. • Generally, we try to group all variables we plan on using, together at the top of the function.

  22. Rules of Precedence a = 5; b = 20; result = a + b / 5 - 1; What value is of ‘result’? answer = b+2 / 2; What is the value is ‘answer’? (Assume that the variables were declared earlier in the script)

  23. Operator Precedence Multiplication and division have higher precedence (they are evaluated before) than addition and subtraction. Operations with the same precedence are evaluated left to right. IMPORTANT: You can use parentheses to force the evaluation order: the innermost ( ) are evaluated first. If you have any doubt when writing an expression, use parentheses.

  24. Precedence practice: What is the order of operations for formulas below? var a, b, position, result; a = 5; b = 20; result = a + b / 2 - 1; Answer: b/2  add to a  subtract 1 (=14) position = a * 5 + b / 10; Answer: a * 5  then b/10  then add the two (=27)

  25. Precedence example: • To convert a temperature from fahrenheit to celcius you must subtract 32, then multiply by 5 and divide over 9. var celsius, far; far = 100; celsius = far - 32 * 5 / 9; //WRONG!!! (Will first do 32*5, then divide by 9, then subtract the total from far) celsius = (far-32) * 5 / 9; // RIGHT! // Anything inside parentheses gets carried out // *first*

  26. Practice: • Create a form that asks the user for a temperature in farheheit. • One text box for the temperature • One button to submit the form • Write a function that outputs the result in celsius. • Output inside an alert box. That is, instead of document.write(…), use alert(….); • Formula: To convert a temperature from fahrenheit to celsius you must subtract 32, then multiply by 5 and divide over 9

  27. The assignment operator: ‘ = ‘ • First the entire right side of the ‘=‘ is evaluated • e.g. a mathematical formula • e.g. retreiving the value from a form • Then the result is stored in the variable on the left. • E.g. • celsius = (far-32) * 5 / 9; • age = document.formName.elementName.value;

  28. Example: x = x + 1 We can add or subtract from the current value of a variable using the example above. If this line of code seems confusing, recall how the assignment operator works (i.e. right-side first  then assignment). x = 5; x = x + 1; alert(x); What’s the value of ‘x’? Again, recall that everything on the right side of the assignment operator (‘=‘) is carried out first. Then the assignment is done. So in this case, x will be set to 6.

  29. Other error values you may encounter NaN Not a number var x = “hello”; x = x * 5; //will generate the ‘NaN’ error // Try it! Infinity Infinity (e.g. 4 / 0) In JavaScript, 4/0 equals “Infinity”. But in mathematics, 4/0 is undefined, which means it has no value.

  30. *** CONDITIONALS: “If…” Types of Conditional statements if statement if-else statement Nested if statements Boolean expressions 30

  31. Example usages: if due date on book is before today’s date charge overdue fee if day of the week is not Sunday or holiday parking meter must be used if number of hours worked is more than 40 pay overtime 31

  32. Types of program execution: Unconditional execution (i.e. no conditionals present) the JavaScript interpreter executes each line in sequence Conditional execution (a conditional IS present) evaluate a condition execute code only if condition is true i.e. the code is not always executed might be a block (several statements) of code controlled by the condition program step 1 program step 2 program step 3 program step 4 program step 5 condition conditional step(s) program step 2 program step 3 program step 4 32

  33. Syntax: The if statement if (condition) { statements } 33

  34. Using braces for ‘if’ statements: If your ‘if’ statement has only one line of code, the braces are optional. if (condition) { statement 1 statement 2 } if (condition) statement In general, I recommend that you ALWAYS use braces until you become very comfortable with this technique. In fact, I’m only showing you the version without braces in case you see it elsewhere. more than one statement – braces are required one statement only – braces are optional 34

  35. The ‘if’ statement (without ‘else’) Conditional execution evaluate a condition execute the set of statements if condition is true do not execute the statements if the condition is false if (condition) conditional true code program step 2 program step 3 program step 4 program step 1 35

  36. Example if (dateToday > dueDate) { 1. calculate fine 2. e-mail overde notice } 36

  37. Curly braces { } are called curly braces or braces. You want to format (e.g. indent) if statements and if-else statements to make your code easier to read by you and by others (colleagues, the grader!, etc). 37

  38. Braces Write them like this: if (condition) { ... body ... } Note how the braces are on separate lines (just as we have been doing with functions). 38

  39. White space is your friend The JavaScript interpreter ignores white space (blank spaces, blank lines, tabs). So, for example, you could write an entire block of code such as an if-statement on one single line: if (condition){ line 1; line 2; line 3; ... } But of course this makes the code harder to read and understand. 39

  40. Example: • Prompt the user for the number of hours they worked. If the hours are over 40, print: “Wow, a hard worker!” • Because we are just testing/practicing, it’s okay to use the prompt function to get input from the user • Remember, that in the real world, we read input from a form • Use document.write to output var hours; hours = document.form.txtHours.value; hours = parseInt(hours); if (hours > 40) { document.write("Wow, a hard worker!"); }

  41. Practice: • Prompt the user for their age. If their age is 18 or more, print: “You can rent a car!” var age; age = document.form.txtAge.value; age = parseInt(age); if (age >= 18) { document.write("You can rent a car!"); }

  42. * The >= operator: • This is a way of saying “equal or greater to”. • In the last example, the conditional: age >= 18 is a way of saying: if the user is equal or greater than 18… You can also use <= to indicate less than or equal to.

  43. Practice: • Prompt the user for the day of the week. If it’s a Sunday, print: “No need to pay the meter!” var day; day = document.form.txtDay.value; if (day == "Sunday") { document.write("No need to pay the meter!"); } ***** Note the comparison operator ‘ == ‘ . If you want to compare two values, you need to use ‘==‘. Using one equals sign ‘=‘ will NOT work. I’ll explain more about this shortly.

  44. The if-else statement Conditional execution evaluate a condition execute one set of statements if condition is true execute the other set of statements if condition is false if (condition) conditional true code else condition false code program step 2 program step 3 program step 4 program step 1 44

  45. Example var age; age = document.form1.txtAge.value; age = parseInt(age); if (age >= 18) { alert("You can rent a car!"); } else { alert("Go find a bike."); } 45

  46. Practice: Ask the user how many hours theyworked in the last week. If they worked more than 40 hours, output “Wow, a hard worker” , if not, output “Better try harder…” Ask their age: If the user’s age is 65 or over, say “You are elegible for retirement benefits”, otherwise, say “Sorry, no benefits yet!” Ask what day it is: If the day is a Sunday, tell them they don’t have to feed the meter. If it is not Sunday, say: “Better get some quarters!” Download ‘basic_form.htm’ (see week 4) and modify it to do the following: 46

  47. If the user worked more than 40 hours, output “wow, a hard worker” , if not, output “Better try harder…” var hours; hours = document.form.txtHours.value; hours = parseInt(hours); if (hours > 40) { document.write("Wow, a hard worker!"); } else { document.write("Better work harder!"); }

  48. Social Security Eligibility: var age; age = document.form.txtAge.value; age = parseInt(age); if ( age >= 65) { document.write("Eligible for SS benefits"); } else { document.write("Wait a few years, sorry."); }

  49. If the day is a Sunday, tell them they don’t have to feed the meter. • If it is not Sunday, say: “Better get some quarters!” • var day; • day = document.form.txtDay.value; • if (day == "Sunday") • { • document.write("No need to pay the meter!"); • } • else • { • document.write("Better get some quarters!"); • }

  50. * if (day == “Sunday”)Why did we need quotes? • Supposing we had instead written: if (day == Sunday) • In this case, JavaScript would think that Sunday was a variable. • By placing the word ‘Sunday’ inside quotations, we are telling JavaScript that we are comparing the variable called ‘day’ with a String of text (value of ‘Sunday’)