Presentation is loading. Please wait.

Presentation is loading. Please wait.

INE1020: Introduction to Internet Engineering 3: Web Page Authoring1 Lecture 5: Introduction to Javascript I r Java and Javascript r Intro. to Javascript.

Similar presentations


Presentation on theme: "INE1020: Introduction to Internet Engineering 3: Web Page Authoring1 Lecture 5: Introduction to Javascript I r Java and Javascript r Intro. to Javascript."— Presentation transcript:

1 INE1020: Introduction to Internet Engineering 3: Web Page Authoring1 Lecture 5: Introduction to Javascript I r Java and Javascript r Intro. to Javascript m Variables & operators m Control Structure m Functions m Duration and Scope

2 INE1020: Introduction to Internet Engineering 3: Web Page Authoring2 1. Java and Javascript r Java m A technology for creating active documents called applets. m Provides high quality animations m Includes an extensive graphics toolkit consisting of run-time support for graphics as well as interface software in the library m Java will NOT be covered in this course since it will be covered in IEG4180 (3rd year). In this course, only Javascript will be covered. r JavaScript is an alternative to Java, it: m incorporates a few basic features of Java m omits many complex features of Java m can be embedded in a standard HTML file. r A browser: m Performs the specified computation m Displays the results m Offers similar functionality as Java

3 INE1020: Introduction to Internet Engineering 3: Web Page Authoring3 1. Java and Javascript r Java m A compiler is needed to convert Java source program into bytecode, understood by Java interpreter m Relatively more complex r Javascript m Simplicity – ease of use m Can be interpreted by browser in its source form m Source representation is less compact than bytecode representation – transporting a source program takes longer time

4 INE1020: Introduction to Internet Engineering 3: Web Page Authoring4 1. Java Applets r Edit  Use an editor, e.g. emacs, notepad, Jbuilder, Visual J++, to type Java program  File has.java extension r Compile m Translates program into bytecodes, understood by Java interpreter m javac myProgram.java  Creates.class file containing bytecodes ( myProgram.class ) r Embed m Embed in HTML document using APPLET tag

5 INE1020: Introduction to Internet Engineering 3: Web Page Authoring5 1. Java Applets r The applet is embedded in an HTML page by using the APPLET tag.

6 INE1020: Introduction to Internet Engineering 3: Web Page Authoring6 r JavaScript scripting language m Originally created by Netscape m Facilitates disciplined approach to designing computer programs m Enhances functionality and appearance of Web pages r Jscript m Microsoft’s version of JavaScript 2. Introduction to JavaScript

7 INE1020: Introduction to Internet Engineering 3: Web Page Authoring7 2. Introduction to JavaScript r Browser includes JavaScript Interpreter m Processes JavaScript commands r Whitespace m Blank lines, space characters, tab characters m Generally ignored by browser m Used for readability and clarity  … tag: m Encloses entire script  Attribute LANGUAGE = “ JavaScript ” Indicates scripting language Tag must be closed at the end of the script

8 INE1020: Introduction to Internet Engineering 3: Web Page Authoring8 2. Introduction to JavaScript r JavaScript is similar to C, C++: m case-sensitive m arithmetic operators: +, -, *, /, % m equality/relational operators: =, m increment/decrement operators: ++, -- m loosely type language - does not require variables to have a type before they can be used. m control structures: selection: if, if/else, switch repetition: while, do/while, for m object libraries: arrays, math functions

9 INE1020: Introduction to Internet Engineering 3: Web Page Authoring9 2. Introduction to JavaScript r A Simple Program: Printing a Line of Text in a Web Page Printing a Line with Multiple Statements document.write( " Welcome to " ); document.writeln( "JavaScript Programming! " );

10 INE1020: Introduction to Internet Engineering 3: Web Page Authoring10 2. Introduction to JavaScript r Correct method call syntax:  object.method( “ string ”, “ [additional arguments] ” );  e.g. document.writeln( “ argument ” ); object = document, method = writeln case-sensitive, like all JavaScript functions Prints the string, which can consist of any text and HTML tags String must be surrounded by quotation marks (“…”) r Statement terminators  All statements must end with semi-colons ( ; ) r Scripts restart when page reloaded/refreshed

11 INE1020: Introduction to Internet Engineering 3: Web Page Authoring11 2.1 JavaScript: Variables r Variables m Location in memory where values are stored m Variable name can be any valid identifier Identifier = series of characters –Letters, digits, underscores (‘ _ ’) and dollar signs (‘ $ ’) –Cannot begin with a digit Valid identifiers: Welcome, $value, _value, m_inputField1, C3PO and R2D2 Invalid identifiers: 7button, Say\Hello and field#5 m Identifiers are case-sensitive

12 INE1020: Introduction to Internet Engineering 3: Web Page Authoring12 2.1 JavaScript: Variables r JavaScript - loosely typed language m Does not require variable to have type before use in program (unlike other languages) m Variable can contain a value of any data type m JavaScript often converts between values of different types automatically r When declaring variables m If not given value, variable has undefined value  To indicate variable has no value, assign it null

13 INE1020: Introduction to Internet Engineering 3: Web Page Authoring13 2.1 JavaScript: Arithmetic Operators r Binary Operators m Used in arithmetic operations  Modulus operator ( % ) m Yields remainder after division m Examples: 43 % 5 = 3 8.7 % 3.4 = 1.9 24 % 6 = 0

14 INE1020: Introduction to Internet Engineering 3: Web Page Authoring14 2.1 JavaScript: Operators’ Precedence r Arithmetic operations  Operate right to left (like the ‘ = ’ sign) r Rules of operator precedence r Operations execute in a specific order

15 INE1020: Introduction to Internet Engineering 3: Web Page Authoring15 2.1 JavaScript Operators r Assignment operations with identical results can be written different ways m Example 1: c = c + 3; m Example 2: c += 3;  Both ways add 3 to the value of c r Example 2 executes faster m Small difference for individual operations m Significant over large number of operations

16 INE1020: Introduction to Internet Engineering 3: Web Page Authoring16 2.1 JavaScript: Arithmetic Assignment Operators

17 INE1020: Introduction to Internet Engineering 3: Web Page Authoring17 2.1 JavaScript: Increment and Decrement Operators  Increment operator ( ++ ) m Example: c++; is identical to c += 1; is identical to c = c + 1;  Decrement operator ( -- ) m Example: c--; is identical to c -= 1; is identical to c = c - 1; r Faster operation – m Save time over many repetitions r Can be preincremented/decremented or postincremented/decremented m Only makes a difference when variable appears in context of larger expression

18 INE1020: Introduction to Internet Engineering 3: Web Page Authoring18 2.1 JavaScript: Pre/Post- Increment/Decrement Operators r Increment and Decrement Operators

19 INE1020: Introduction to Internet Engineering 3: Web Page Authoring19 2.1 JavaScript Operators r Equality and Relational Operators used in decision making  if structure: m Program makes decision based on truth or falsity of condition If condition met (true) –Statement(s) in body of structure executed If condition not met (false) –Statement(s) in body of structure skipped

20 INE1020: Introduction to Internet Engineering 3: Web Page Authoring20 2.1 JavaScript: Equality and Relational Operators

21 INE1020: Introduction to Internet Engineering 3: Web Page Authoring21 2.1 JavaScript: Logical Operators r Logical operators m Used to form more complex conditions by combining simple conditions r Logical operators are  && (logical AND)  || (logical OR)  ! (logical NOT or logical negation)

22 INE1020: Introduction to Internet Engineering 3: Web Page Authoring22 Rules for Forming Structured Programs r Rule 1: Begin with the “simplest flowchart” r Rule 2: Any rectangle (action) can be replaced by two rectangles (actions) in sequence  Rule 3: Any rectangle (action) can be replaced by any control structure (sequence, if, if/else, switch, do/while or for ) r Rules 2 and 3 may be applied as often as you like and in any order 2.2 JavaScript: Structured Programming

23 INE1020: Introduction to Internet Engineering 3: Web Page Authoring23 2.2 JavaScript: Structured Programming r Repeatedly Applying Rule 2 to the Simplest Flowchart Rule 2

24 INE1020: Introduction to Internet Engineering 3: Web Page Authoring24 2.2 JavaScript: Structured Programming r Applying Rule 3 to the Simplest Flowchart Rule 3

25 INE1020: Introduction to Internet Engineering 3: Web Page Authoring25 2.2 JavaScript: Control Structures r Structured approach: 7 single-entry/single- exit pieces m Selection control structures if structure (single selection) if/else structure (double selection) switch structure (multiple selection) m Repetition control structures while structure do/while structure for structure for/in structure

26 INE1020: Introduction to Internet Engineering 3: Web Page Authoring26

27 INE1020: Introduction to Internet Engineering 3: Web Page Authoring27 2.2 JavaScript: Control Structures r All control structure names are keywords m Reserved by language for feature implementation r May not be used as variable names

28 INE1020: Introduction to Internet Engineering 3: Web Page Authoring28 2.2 JavaScript: Control Structures r Any form of control in JavaScript can be expressed through  if structure (selection)  while structure (repetition) r Control structures combined in two ways m Control-structure stacking Single-entry/single-exit structures m Control-structure nesting r Program readability: m Indent statements in body of each control structure m Blank line before and after each major control structure m Avoid more than three levels of nesting

29 INE1020: Introduction to Internet Engineering 3: Web Page Authoring29 2.2 JavaScript: If/Else Selection Structure r Flowchart: r JavaScript statement: if ( grade >= 60 ) document.writeln( “ Passed ” ); else document.writeln( “ Failed ” ); print “Passed” grade >= 60 print “Failed” FalseTrue

30 INE1020: Introduction to Internet Engineering 3: Web Page Authoring30 2.2 JavaScript: If/Else Selection Structure m JavaScript interpreter Associates else statement with previous if statement unless indicated otherwise by braces ( {} ) m Example: if ( x > 5 ) if ( y > 5 ) document.writeln( “ x and y are > 5 ” ); else document.writeln( “ x is <= 5 ” ); Because of indent, appears that else statement applies to first if statement But in fact, it is applied to the second if statement

31 INE1020: Introduction to Internet Engineering 3: Web Page Authoring31 2.2 JavaScript: If/Else Selection Structure  To have JavaScript interpret the structure correctly, utilize braces ( {} ) if ( x > 5 ) { if ( y > 5 ) document.writeln( “ x and y are > 5 ” ); } else document.writeln( “ x is <= 5 ” );  else statement now applies to first if statement

32 INE1020: Introduction to Internet Engineering 3: Web Page Authoring32 2.2 Switch structure Switching between XHTML List Formats var choice, // user’s choice startTag, // starting list item tag endTag, // ending list item tag validInput = true, // indicates if input is valid listType; // list type as a string choice = window.prompt( "Select a list style:\n" + "1 (bullet), 2 (numbered), 3 (lettered)", "1" );

33 INE1020: Introduction to Internet Engineering 3: Web Page Authoring33 2.2 Switch structure switch ( choice ) { case "1": startTag = " "; endTag = " "; listType = " Bullet List "; break; case "2": startTag = " "; endTag = " "; listType = " Ordered List: Numbered "; break; case "3": startTag = " "; endTag = " "; listType = " Ordered List: Lettered "; break; default: validInput = false; }

34 INE1020: Introduction to Internet Engineering 3: Web Page Authoring34 2.2 Switch structure if ( validInput == true ) { document.writeln( listType + startTag ); for ( var i = 1; i <= 3; ++i ) document.writeln( " List item " + i + " " ); document.writeln( endTag ); } else document.writeln( "Invalid choice: " + choice ); // -->

35 INE1020: Introduction to Internet Engineering 3: Web Page Authoring35 2.2 Switch structure: Program Output

36 INE1020: Introduction to Internet Engineering 3: Web Page Authoring36 2.2 Switch structure Program Output

37 INE1020: Introduction to Internet Engineering 3: Web Page Authoring37 9.5 switch Multiple-Selection Structure...... Fig. 9.8switch multiple-selection structure.

38 INE1020: Introduction to Internet Engineering 3: Web Page Authoring38 2.2 JavaScript: While Repetition Structure r Counter-controlled repetition requires: 1. Name of control variable (or loop counter) 2. Initial Value of control variable 3. Increment (or decrement) of control variable per loop 4. Condition that tests for final value of control variable r Equivalent Structures  for structure: for ( initialization; loopContinuationTest; increment ) statement;  while structure: initialization; while ( loopContinuationTest ) { statement; increment; }

39 INE1020: Introduction to Internet Engineering 3: Web Page Authoring39 2.2 JavaScript: While Repetition Structure r Example: Printing a text with increasing font size. r Flowchart: var counter = 1 document.writeln( “ <FONT SIZE = ” + counter + “ >HTML Font size ” + counter + “ ” ); counter <= 7 True False Establish initial value of control variable Determine if final value of control variable has been reached Body of loop (this may be many statements ++counter Increment the control variable

40 INE1020: Introduction to Internet Engineering 3: Web Page Authoring40 2.2 JavaScript: While Repetition Structure r Script source code: Counter-Controlled Repetition var counter = 1; // initialization while ( counter <= 7 ) { // repetition condition document.writeln( " <FONT SIZE = '" + counter + "'>HTML font size " + counter + " " ); ++counter; // increment }

41 INE1020: Introduction to Internet Engineering 3: Web Page Authoring41 2.2 JavaScript: While Repetition Structure r Script output:

42 INE1020: Introduction to Internet Engineering 3: Web Page Authoring42 Counter-Controlled Repetition var counter = 1; do { document.writeln( " This is " + "an h" + counter + " level head" + "</h" + counter + ">" ); ++counter; } while ( counter <= 6 ); 2.2 JavaScript: Do/While Repetition Structure condition true action(s) false

43 INE1020: Introduction to Internet Engineering 3: Web Page Authoring43 2.2 JavaScript: Do/While Repetition Structure Script output:

44 INE1020: Introduction to Internet Engineering 3: Web Page Authoring44 2.2 Alter Flow r The break and continue Statements m Alter flow of control r break; m Exits structure r continue; m Skips remaining statements in structure; continues with next loop iteration r When used properly m Performs faster than the corresponding structured techniques

45 INE1020: Introduction to Internet Engineering 3: Web Page Authoring45 2.2 For Repetition Structure and Break r Example of break statement: Using the break Statement in a for Structure for ( var count = 1; count <= 10; ++count ) { if ( count == 5 ) break; // break loop only if count == 5 document.writeln( "Count is: " + count + " " ); } document.writeln( "Broke out of loop at count = " + count );

46 INE1020: Introduction to Internet Engineering 3: Web Page Authoring46 2.2 For Repetition Structure and Break r Script output:

47 INE1020: Introduction to Internet Engineering 3: Web Page Authoring47 2.2 For Repetition Structure and Continue r Example of continue statement: Using the continue Statement in a for Structure for ( var count = 1; count <= 10; ++count ) { if ( count == 5 ) continue; // skip remaining code in loop only if count == 5 document.writeln( "Count is: " + count + " " ); } document.writeln( "Used continue to skip printing 5");

48 INE1020: Introduction to Internet Engineering 3: Web Page Authoring48 2.2 For Repetition Structure and Continue r Script output:

49 INE1020: Introduction to Internet Engineering 3: Web Page Authoring49 2.3 Program Modules in JavaScript r functions – JavaScript modules r JavaScript programs written by combining m Functions programmer writes m “prepackaged” functions and objects in JavaScript These functions often called methods Implies function belongs to particular object r JavaScript provides several rich objects for performing m Common mathematical operations m String manipulation m Date and time manipulation m Manipulations of arrays

50 INE1020: Introduction to Internet Engineering 3: Web Page Authoring50 2.3 Program Modules in JavaScript r Programmer-defined functions m Written by programmer to define specific tasks m Statements defining functions written once m Statements are hidden from other functions r Function is invoked by a function call m Specifies function name m Provides information (or arguments) function needs for execution r Function call syntax: functionName( argument );

51 INE1020: Introduction to Internet Engineering 3: Web Page Authoring51 2.3 Program Modules in JavaScript r Functions allow program modularization r Variables declared in function are local variables m Only known inside function in which defined r Most functions have list of parameters m Means for communicating info between functions & function calls m Local variables m When function called, arguments assigned to parameters in function definition

52 INE1020: Introduction to Internet Engineering 3: Web Page Authoring52 2.3 Program Modules in JavaScript r Motives for modularizing a program with functions m Makes program development more manageable m Allows software reusability Programs can be created from standard functions instead of being built from customized code Example: parseInt(), parseFloat Functions should be limited to performing a single, well- defined task m Avoid repeating code in program Do not re-invent the wheel Save time

53 INE1020: Introduction to Internet Engineering 3: Web Page Authoring53 2.3 Function Definitions r Function-definition format function function-name ( parameter-list ) { Declarations and Statements } m Function name - any valid identifier m Parameter list - comma-separated list containing names of parameters received by the function when it is called m If function does not receive values, parameter-list is left empty

54 INE1020: Introduction to Internet Engineering 3: Web Page Authoring54 2.3 Function Definitions r Function body or block: m declarations and statements within braces r Control m Returned to the point at which function was called m If function does not return a result When right-brace is reached return statement is executed m If function returns a result When return expression; is executed Returns value of expressions to caller r One argument in function call for each parameter in function definition

55 INE1020: Introduction to Internet Engineering 3: Web Page Authoring55 2.3 Function Definitions r Example of function definitions to calculate the square of a number A Programmer-Defined square Function document.writeln(" Square the numbers from 1 to 10 " ); // square the numbers from 1 to 10 for ( var x = 1; x <= 10; ++x ) document.writeln( "The square of " + x + " is " + square( x ) + " " ); // The following square function's body is executed only // when the function is explicitly called. // square function definition function square( y ) { return y * y; }

56 INE1020: Introduction to Internet Engineering 3: Web Page Authoring56 2.3 Function Definitions r Script output:

57 INE1020: Introduction to Internet Engineering 3: Web Page Authoring57 2.4 Identifier Duration and Scope r Each identifier has duration and scope m Duration (or lifetime) is the period during which identifier exists in memory. Some identifiers exist briefly Some identifiers are repeatedly created and destroyed Some identifiers exist for entire execution of the program r Identifiers which represent local variables in a function have automatic duration m Automatically created when program control enters function m Exist while function is active m Automatically destroyed when function is exited m Referred to as local variables

58 INE1020: Introduction to Internet Engineering 3: Web Page Authoring58 2.4 Identifier Duration and Scope r JavaScript also has identifiers of static duration m Typically defined in section of HTML document m Exist from point at which declared until browsing session over m Referred to as global variables or script-level variables

59 INE1020: Introduction to Internet Engineering 3: Web Page Authoring59 2.4 Identifier Duration and Scope r Scope of identifier is portion of program in which identifier can be referenced m Local variable declared in a function can be used only in that function r Identifiers declared inside a function have function (or local) scope  Begins with opening brace ( { ) of function  Ends with closing brace( } ) of function m Function parameters also have local scope m If local variable has same name as global variable, global variable is hidden from body of function

60 INE1020: Introduction to Internet Engineering 3: Web Page Authoring60 2.4 Identifier Duration and Scope r Example demonstrating the scoping issues with global variables and local variables. A Scoping Example var x = 1; // global variable function start() { var x = 5; // variable local to function start document.writeln( "local x in start is " + x ); functionA(); // functionA has local x functionB(); // functionB uses global variable x functionA(); // functionA reinitializes local x functionB(); // global variable x retains its value document.writeln( " local x in start is " + x + " " ); }

61 INE1020: Introduction to Internet Engineering 3: Web Page Authoring61 2.4 Identifier Duration and Scope function functionA() { var x = 25; // initialized each time function A is called document.writeln( " local x in functionA is " + x + " after entering functionA" ); ++x; document.writeln( " local x in functionA is " + x + " before exiting functionA " ); } function functionB() { document.writeln( " global variable x is " + x + " on entering functionB" ); x *= 10; document.writeln( " global variable x is " + x + " on exiting functionB " ); }

62 INE1020: Introduction to Internet Engineering 3: Web Page Authoring62 2.4 Identifier Duration and Scope r Script output:

63 INE1020: Introduction to Internet Engineering 3: Web Page Authoring63 2.4. JavaScript Predefined (or Global) Functions

64 INE1020: Introduction to Internet Engineering 3: Web Page Authoring64 2.4. JavaScript Predefined (or Global) Functions

65 INE1020: Introduction to Internet Engineering 3: Web Page Authoring65 Further Readings r Note: This topic is designed with the objective of providing an introduction to Javascript. r Advanced features of Javascript are beyond the scope of this course and will NOT be taught or discussed. Students who wish to invest more time on studying advanced features and topics of Javascript are referred to the following resources: m Deitel Chapter 7-10 m http://developer.netscape.com/docs/manuals/javascript.html http://developer.netscape.com/docs/manuals/javascript.html


Download ppt "INE1020: Introduction to Internet Engineering 3: Web Page Authoring1 Lecture 5: Introduction to Javascript I r Java and Javascript r Intro. to Javascript."

Similar presentations


Ads by Google