Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript: Control Structures September 27, 2005 Slides modified from Internet & World Wide Web: How to Program. 2004 (3rd) edition. By Deitel, Deitel,

Similar presentations


Presentation on theme: "JavaScript: Control Structures September 27, 2005 Slides modified from Internet & World Wide Web: How to Program. 2004 (3rd) edition. By Deitel, Deitel,"— Presentation transcript:

1 JavaScript: Control Structures September 27, 2005 Slides modified from Internet & World Wide Web: How to Program. 2004 (3rd) edition. By Deitel, Deitel, and Goldberg. Published by Prentice Hall. ISBN 0-13-145091-3

2 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing a Line of Text in a Web Page 7.3 Obtaining User Input with prompt Dialogs 7.3.1Dynamic Welcome Page 7.3.2Adding Integers 7.4 Memory Concepts 7.5 Arithmetic 7.6 Decision Making: Equality and Relational Operators 7.7 Web Resources

3 Objectives In this lesson, you will learn: –To be able to write simple JavaScript programs. –To be able to use input and output statements. –To understand basic memory concepts. –To be able to use arithmetic operators. –To understand the precedence of arithmetic operators. –To be able to write decision-making statements. –To be able to use relational and equality operators.

4 Introduction to JavaScripting

5 7.1 Introduction JavaScript scripting language –Enhances functionality and appearance –Client-side scripting Makes pages more dynamic and interactive –Foundation for complex server-side scripting –Program development –Program control

6 What can JavaScript programs do? From http://www.javascripter.net/faq/javascri.htmhttp://www.javascripter.net/faq/javascri.htm Giving the user more control over the browser Detecting the user's browser, OS, screen size, etc. Performing simple computations on the client side Validating the user's input Handling dates and time Generating HTML pages on-the-fly without accessing the Web server.

7 What can’t JavaScript programs do? From http://www.javascripter.net/faq/javascr2.htmhttp://www.javascripter.net/faq/javascr2.htm Use printers or other devices on the user's system or the client-side LAN Directly access files on the user's system or the client-side LAN ; the only exception is the access to the browser's cookie files. Directly access files on the Web server. Implement multiprocessing or multithreading.

8 Programming context Interpreted language Web browser as the interpreter Client-side only –Compatibility depends on browser version But virtually every browser supports JavaScript Follow ECMAScript standard!ECMAScript –Security issues You cannot access the client’s system beyond their web browser –Thus, no file access or direct printing

9 Notes on compatibility Browser versions –80-90% of people user Internet Explorer Of which 99% use IE 6 or IE 5 –10-15% use Gecko-based browsers Firefox, Netscape, Mozilla JavaScript and cookies –Only 85-90% have JavaScript enabled –Cookies usually enabled by default—I don’t have statistics for how many leave this on Screen resolutions –25% use 800x600 –70% use 1024x768 or higher Recommendations: –Test all pages with IE 5/6 and Firefox –Don’t assume that users have JavaScript or cookies enabled Your site should still be functional without client-side scripting or cookies –Design to be comfortably viewable with 800x600 resolution Sources –http://www.upsdell.com/BrowserNews/stat_trends.htmhttp://www.upsdell.com/BrowserNews/stat_trends.htm –http://www.w3schools.com/browsers/browsers_stats.asphttp://www.w3schools.com/browsers/browsers_stats.asp

10 Object orientation in JavaScript JavaScript is an object-oriented programming language –Based on objects with properties and methods JavaScript uses prototyping to replicate behaviour, rather than classification (classes) There are two types of variables: –Simple variables (also called “primitives”) –Objects

11 Objects in JavaScript An object is a complex type of variable that contains its own variables (properties), and has its own functions (methods) –Properties The variables of an object Can also be other objects –Methods The functions that belong to an object –e.g. document.bgColor, window.location JavaScript has a rich set of built-in objects –http://www.devguru.com/Technologies/ecmascript/quickref/js_objects.ht mlhttp://www.devguru.com/Technologies/ecmascript/quickref/js_objects.ht ml You can also define your own objects

12 How to specify JavaScript code Inline Code –Add dynamic functionality to an individual element Write JavaScript code directly in appropriate event attributes Embedded scripts –Embed JavaScript code in an XHTML document—either in the head or in the body x=3; y=9; document.writeln( x + y ); Inserting external scripts –Insert a file with “.js” extension that contains JavaScript code JavaScript libraries can be shared by multiple XHTML documents A note on CDATA – –Necessary for legal XML to ignore & and < symbols (which are common in scripts) –However, most browsers work fine without them –http://www.w3schools.com/xml/xml_cdata.asphttp://www.w3schools.com/xml/xml_cdata.asp –The textbook says to use But CDATA is proper XML syntax Comments should validate, but not guaranteed

13 First scripts

14 7.2 Simple Program: Printing a Line of Text in a Web Page Inline scripting –Written in the of a document – tag Indicate that the text is part of a script type attribute –Specifies the type of file and the scripting language use writeln method –Write a line in the document Escape character ( \ ) –Indicates “special” character is used in the string alert method –Dialog box

15 welcome.html (1 of 1)

16 welcome2.html (1 of 1)

17 welcome3.html 1 of 1

18 welcome4.html 1 of 1

19 Illegal characters in XHTML vs. JavaScript XHTML –HTML entities & < > Others: http://www.w3schools.com/tags/ref_entities.asphttp://www.w3schools.com/tags/ref_entities.asp JavaScript –Escape sequences \’ \” \n \t \\ Others: http://www.devguru.com/Technologies/ecmascript/quickref/escaped_characters.html http://www.devguru.com/Technologies/ecmascript/quickref/escaped_characters.html To convert between the two, use an XHTML  JavaScript converter –Google “HTML JavaScript converter” –Best that I’ve found: http://javascript.about.com/library/blscr02.htm

20 7.2 Common escape sequences For full list, see http://www.devguru.com/Technologies/ecmascript/quickref/escaped_characters.html http://www.devguru.com/Technologies/ecmascript/quickref/escaped_characters.html

21 7.3.1 Dynamic Welcome Page A script can adapt the content based on input from the user or other variables

22 welcome5.html (1 of 2)

23 7.3.1 Dynamic Welcome Page Fig. 7.7Prompt dialog displayed by the window object’s prompt method. This is the prompt to the user. This is the default value that appears when the dialog opens. This is the text field in which the user types the value. When the user clicks OK, the value typed by the user is returned to the program as a string.

24 JavaScript data types In JavaScript, you can use the var statement to create a variable, but it is not required You do not declare any data type (loosely typed) –For scripting languages, data types are automatically determined –Automatically converts between values of different types JavaScript data types –Numbers Numbers are numbers, whether integer or floating point –Boolean values true or false –Strings “Anything within quotes” ‘Anything within quotes’ –Null "special key word denoting a null value" Means “no value” –From http://www.ryerson.ca/JavaScript/lectures/basicDataTypes/basicTypes.htmlhttp://www.ryerson.ca/JavaScript/lectures/basicDataTypes/basicTypes.html

25 7.3.2 Adding Integers Prompt user for two integers and calculate the sum (Fig. 7.8) NaN (not a number) parseInt –Converts its string argument to an integer

26 Addition.html (1 of 2)

27 JavaScript native functions See http://www.devguru.com/Technologies/ecmascript/quickref/js_functions.html http://www.devguru.com/Technologies/ecmascript/quickref/js_functions.html parseInt() –Converts a string into an integer, if possible parseFloat () –Converts a string into a floating-point number, if possible string () –Converts any object into a string number () –Converts any object into a number, if possible isNAN () –true if the object is Not A Number escape() and unescape() –Converts and deconverts strings to “safe” characters

28 Operators in JavaScript http://www.devguru.com/Technologies/ecmascript/quickref/js_operators.html

29 7.5 Arithmetic operators

30 7.6 Decision Making: Equality and Relational Operators  

31 welcome6.html (1 of 3)

32 welcome6.html (2 of 3)

33 7.6 Decision Making: Equality and Relational Operators

34 Chapter 8 - JavaScript: Control Statements I Outline 8.1 Introduction 8.2 Algorithms 8.3 Pseudocode 8.4 Control Structures 8.5 if Selection Statement 8.6 if…else Selection Statement 8.7 while Repetition Statement 8.8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) 8.9 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) 8.10 Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3 (Nested Control Structures) 8.11 Assignment Operators 8.12 Increment and Decrement Operators 8.13 Note on Data Types 8.14 Web Resources

35 Objectives In this lesson, you will learn: –To understand basic problem-solving techniques. –To be able to develop algorithms through the process of top-down, stepwise refinement. –To be able to use the if and if … else selection statements to choose among alternative actions. –To be able to use the while repetition statement to execute statements in a script repeatedly. –To understand counter-controlled repetition and sentinel-controlled repetition. –To be able to use the increment, decrement and assignment operators.

36 8.1 Introduction Writing a script –Thorough understanding of problem –Carefully planned approach –Understand the types of building blocks that are available –Employ proven program-construction principles

37 8.4 Control Structures Sequential execution –Statements execute in the order they are written Transfer of control –Next statement to execute may not be the next one in sequence Three control structures –Sequence structure –Selection structure if if … else switch –Repetition structure while do … while for for … in

38 8.4 JavaScript keywords

39 8.5 if Selection Statement Single-entry/single-exit structure Indicate action only when the condition evaluates to true Indicate different actions to be perform when condition is true or false Conditional operator ( ?: ) –JavaScript’s only ternary operator Three operands Forms a conditional expression

40 8.7 while Repetition Statement Repetition structure (loop) –Repeat action while some condition remains true

41 8.10 Formulating Algorithms with Top- Down, Stepwise Refinement: Case Study 3 (Nested Control Structures) Consider problem Make observations Top-down, stepwise refinement

42 analysis.html (1 of 2)

43

44 More on JavaScript operators

45 8.11 Compound Assignment Operators

46 8.12 Increment and Decrement Operators Preincrement or predecrement operator –Increment of decrement operator placed before a variable Postincrement or postdecrement operator –Increment of decrement operator placed after a variable

47 8.12 Increment and Decrement Operators

48 increment.html (1 of 2)

49 8.12 Increment and Decrement Operators

50 Chapter 9 - JavaScript: Control Statements II Outline 9.1 Introduction 9.2 Essentials of Counter-Controlled Repetition 9.3 for Repetition Statement 9.4 Examples Using the for Statement 9.5 switch Multiple-Selection Statement 9.6 do … while Repetition Statement 9.7 break and continue Statements 9.8 Labeled break and continue Statements 9.9 Logical Operators 9.10 Summary of Structured Programming 9.11Web Resources

51 Objectives In this lesson, you will learn: –To be able to use the for and do … while repetition statements to execute statements in a program repeatedly. –To understand multiple selection using the switch selection statement. –To be able to use the break and continue program-control statements. –To be able to use the logical operators.

52 9.2 Essentials of Counter- Controlled Repetition Counter-controlled repetition –Name of a control –Initial value –Increment or decrement –Final value

53 WhileCounter.html (1 of 2)

54 9.3 for Repetition Statement for repetition statement –Handles all the details of counter-controlled repetition –for structure header The first line

55 ForCounter.html (1 of 1)

56 9.3 for Repetition Statement for (var counter =1; counter <=7; ++counter ) Initial value of control variable Increment of control variable Control variable name Final value of control variable for which the condition is true for keyword Loop-continuation condition Fig. 9.3 for statement header components.

57 9.4 Examples Using the for Statement Summation with for Compound interest calculation with for loop –Math object Method pow Method round

58 Sum.html (1 of 1)

59 Interest.html (1 of 2)

60 9.5 switch Multiple- Selection Statement Controlling expression Case labels Default case

61 SwitchTest.html (1 of 3)

62 SwitchTest.html (2 of 3)

63 9.6 do … while Repetition Statement Similar to the while statement Tests the loop continuation condition after the loop body executes Loop body always executes at least once

64 DoWhileTest.html (1 of 2)

65 9.7 break and continue Statements break –Immediate exit from the structure –Used to escape early from a loop –Skip the remainder of a switch statement continue –Skips the remaining statements in the body of the structure –Proceeds with the next iteration of the loop

66 BreakTest.html (1 of 2)

67 ContinueTest.html (1 of 2)

68 9.8 Labeled break and continue Statements Labeled break statement –Break out of a nested set of structures –Immediate exit from that structure and enclosing repetition structures –Execution resumes with first statement after enclosing labeled statement Labeled continue statement –Skips the remaining statements in structure’s body and enclosing repetition structures –Proceeds with next iteration of enclosing labeled repetition structure –Loop-continuation test evaluates immediately after the continue statement executes

69 BreakLabelTest.html (1 of 2)

70 ContinueLabelTest.html (1 of 2)

71 Logical operators

72 9.9 Logical Operators More logical operators –Logical AND ( && ) –Logical OR ( || ) –Logical NOT ( ! )

73 9.9 Logical Operators

74

75 LogicalOperators.html (1 of 2)

76 9.9 Logical Operators

77 Conclusion to JavaScript introduction

78 9.10 Summary of Structured Programming Flowcharts –Reveal the structured nature of programs Single-entry/single-exit control structures –Only one way to enter and one way to exit each control structure Control structure stacking –The exit point of one control structure is connected to the entry point of the next control structure

79 When things go wrong: Debugging JavaScript Taken from http://www.ryerson.ca/JavaScript/lectures/scriptTags/debugging.htmlhttp://www.ryerson.ca/JavaScript/lectures/scriptTags/debugging.html JavaScript is case sensitive –Document.write() will not work. Neither will document.Write(). Almost every object, property, and method name like document and write() begin with a lower case letter. In cases like document.bgColor the second word in an object, property, or method name is almost always capitalized. I.e. the C in bgColor but nothing else. Use the American spelling of color –There is no colour property. Don't forget the closing bracket, and don’t forget both quotes –Make sure your pairs of (parentheses) and “double quotes” or ‘single quotes’ all match Spelling counts –Drop the e in document and watch what happens. The order you do things in matters –If you set the background colour in the head of the document the document background colour may not change. If you set it in the body it will. Watch out for quotes inside quotes –Whenever you write out an HTML tag with an attribute that requires quotes you must escape the quote inside the tag by placing a backslash just before it. –For example document.write(" A LINK ") will produce an error. –Escaping the quotes will fix this: document.write(" A LINK "). –Make sure you escape both of them.

80 8.14 Web Resources http://www.javascripter.net/faq/index.htm http://www.ecma- international.org/publications/standards/Ecma-262.htmhttp://www.ecma- international.org/publications/standards/Ecma-262.htm http://www.devguru.com/Technologies/ecmascript/quickr ef/javascript_index.htmlhttp://www.devguru.com/Technologies/ecmascript/quickr ef/javascript_index.html http://javascript.about.com/library/blscr02.htm http://www.ryerson.ca/JavaScript/lectures/ www.javascriptmall.com developer.netscape.com/tech/javascript www.mozilla.org/js/language


Download ppt "JavaScript: Control Structures September 27, 2005 Slides modified from Internet & World Wide Web: How to Program. 2004 (3rd) edition. By Deitel, Deitel,"

Similar presentations


Ads by Google