Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to JavaScript 21 Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 15.

Similar presentations


Presentation on theme: "Introduction to JavaScript 21 Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 15."— Presentation transcript:

1 Introduction to JavaScript 21 Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 15

2 Introduction to JavaScript 22 Today’s Topics Working with objects JavaScript data types and operators Conditional and loop statements Using events

3 Introduction to JavaScript 23 Review: A First JavaScript Program The Tag  JavaScript programs are run from within an HTML document  and Used to notify the browser that JavaScript statements are contained within

4 Introduction to JavaScript 24 Review: A First JavaScript Program The Tag  language attribute Denotes the scripting language being used  Default  JavaScript  Other languages (e.g., VBScript) may be used  Can also specify script language version No space between name and version Checked by browser, scripts ignored if browser doesn’t support version  For ECMAScript compatible browsers, omit version

5 Introduction to JavaScript 25

6 6 Review: Working with Variables Variables  To create: Use keyword var to declare the variable Use the assignment operator to assign the variable a value  Declare, then assign value (initialize) var employeeName; employeeName = “Ric”;  Declare and assign variable in a single statement var employeeName = “Ric”;

7 Introduction to JavaScript 27 Review: Working with Functions Defining Custom Functions  A function definition consists of three parts: Reserved word function followed by the function name (identifier) Parameters required by the function, contained within parentheses following the name  Parameters  variables used within the function  Zero or more may be used Function statements, delimited by curly braces { }

8 Introduction to JavaScript 28

9 9 Some Built-in Functions http://www.devguru.com/Technologies/ecmascript/quickref/js_functions.html

10 Introduction to JavaScript 210 Working with Objects An object is a collection of properties and these properties include:  Primitive data types  Other objects  Functions(methods) Constructor function(constructor) is a function to create an instance of the object Use the new keyword with the constructor to create a new object You access the property that belongs to an object using the dot access operator, “.” :  document.writeln(``my message’’);  Some_variable: = document.form_name.input_element_name.value;

11 Introduction to JavaScript 211 Objects There are built-in objects that relate to the browser and its contents:  Window  Document  Navigator  Frames  Location  History  … These objects are global objects and you need not create a new instance when you use them

12 Introduction to JavaScript 212

13 Introduction to JavaScript 213 Working with Objects There are also built-in JavaScript objects that extend the functionality of the language: JavaScript includes 11 built-in objects that relate to the language itself Each object contains various methods and properties for performing a particular task Can be used directly in program without instantiating a new object

14 Introduction to JavaScript 214

15 Introduction to JavaScript 215 Working with Objects JavaScript built-in object properties and methods reference  http://archive.devx.com/projectcool/developer/ reference/jscript_obj.html http://archive.devx.com/projectcool/developer/ reference/jscript_obj.html

16 Introduction to JavaScript 216 Working with Objects Custom JavaScript objects (not required in this course)  Based on constructor functions Instantiate a new object or extending an old object Objects inherit all variables and statements of constructor function  Any JavaScript function can serve as a constructor Online reference:  http://www.sitepoint.com/article/oriented- programming-1/2 http://www.sitepoint.com/article/oriented- programming-1/2

17 Introduction to JavaScript 217 JavaScript Data Types Data Types  Primitive data types Data types that can be assigned only a single value JavaScript supports five primitive data types  Integers  Floating points  Booleans  Strings  Null

18 Introduction to JavaScript 218

19 Introduction to JavaScript 219 Using Data Types Data Types  Primitive data types (cont’d) Null value  Data type and a value  Signifies that the variable contains no value Undefined variable  Has never had a value assigned to it  Has not been declared or  Does not exist

20 Introduction to JavaScript 220 Using Data Types Data Types  Reference (composite) data types Collections of data represented by a single variable name JavaScript supports three reference data types  Functions  Objects  Arrays

21 Introduction to JavaScript 221 Using Data Types Data Types  Strongly typed programming languages Data types do not change after they have been declared (data type declaration required) Also know as static typing  Loosely typed programming languages Variable data types are not required to be declared Also know as dynamic typing

22 Introduction to JavaScript 222 Using Data Types Data Types  JavaScript language Loosely typed programming language JavaScript does not allow data typing Determined automatically by JavaScript interpreter  Can be determined using typeof() operator typeof(variableName)  PrintDataTypes.html PrintDataTypes.html

23 Introduction to JavaScript 223

24 Introduction to JavaScript 224 Using Data Types Numeric Data Types  JavaScript supports two numeric data types Integers  Positive or negative number with no decimal point  Range from –2 53 to 2 53 Floating points  Contains decimal places or written using exponential notation  Range from  1.7976931348623157 X 10 308 to  5 X 10 -324

25 Introduction to JavaScript 225 Using Data Types Boolean Values  Logical value of true or false Can be thought of as yes/on/1 or no/off/0  Used for decision making and comparing data Recall use in overriding internal event handler with custom code

26 Introduction to JavaScript 226 Using Data Types Strings  Text string contains zero or more characters delimited by double or single quotation marks  Text strings can be: Used as literal values Assigned to a variable Assigned a zero-length string value (empty string)

27 Introduction to JavaScript 227 Using Data Types Strings  Using quotation marks and apostrophes Use one to delimit and the other in the literal  var thisString = “Dave’s house”;  var anotherString = ‘The “house” of Dave’; Or, use escape sequence  var aThirdString = ‘Dave\’s house’;

28 Introduction to JavaScript 228

29 Introduction to JavaScript 229

30 Introduction to JavaScript 230

31 Introduction to JavaScript 231

32 Introduction to JavaScript 232

33 Introduction to JavaScript 233 Using Data Types Strings  Using HTML tags in strings Use tags to format strings  Tag must be contained inside string quotes  var newString = “Dave’s house. ”;

34 Introduction to JavaScript 234 Using Data Types Arrays  Contains a set of data represented by a single variable name i.e., collection of variables contained in a single variable Used to store related things To create, use Array() constructor function  hospitalDepartments = new Array(numberOfElements);

35 Introduction to JavaScript 235 Using Data Types Arrays  Each piece of data in array is an element  Numbering of elements in array starts with 0  Size of array is declared and each element in array is accessed using brackets [ ] hospitalDepartments = new Array(10); hospitalDepartments[0] = “Oncology”;  Arrays can contain different data types  Array elements are undefined unless value is assigned

36 Introduction to JavaScript 236 Array Built-in Methods  myArray.length length return the number of elements in the array (which is alway one less than the last index).  myArray.sort() sort() sorts an array in alphabetical order.  myArray.push([value]) push([value]) appends value to the end of the array.  myArray.pop() pop() extracts and returns the last item of the array.

37 Introduction to JavaScript 237 Array Built-in Methods (cont’d)  myArray.unshift([value] unshift([value]) inserts value at the from of the array.  myArray.shift() shift() extracts and returns the first item of the array.  Online references: http://www.classes.cs.uchicago.edu/classes/archive/2004/win ter/10100-1/02/javascript/arrayMethods.html http://www.classes.cs.uchicago.edu/classes/archive/2004/win ter/10100-1/02/javascript/arrayMethods.html http://developer.netscape.com/viewsource/goodman_arrays. html http://developer.netscape.com/viewsource/goodman_arrays. html

38 Introduction to JavaScript 238 Automatic Arrays in Document Objects Some objects in the document object model can contain more than one nested object of the same type  Example: list of all links or a list of all forms or a list of all components in a form  http://archive.devx.com/projectcool/developer/referen ce/jscript_obj.html http://archive.devx.com/projectcool/developer/referen ce/jscript_obj.html The browser automatically maintains arrays of those items  Example: document.links, document.forms, document.forms[0].elements

39 Introduction to JavaScript 239 Automatic Arrays in Document Objects (cont’d) How to access the object in these arrays, for example, a link in the document?  By array syntax. If this link is the first link definition in the document (in source code order), the reference would be document.links[0]  Or you can also use the name (as a string) in array syntax, as follows: document.links["home"] Does not work in IE!  Examples: http://people.cs.uchicago.edu/~hai/hw6/accessobject.html

40 Introduction to JavaScript 240 Expressions and Operators Expressions  Combination of literal values, variables, operators, and other expressions that can be evaluated by the JavaScript interpreter to produce a result

41 Introduction to JavaScript 241

42 Introduction to JavaScript 242 Expressions and Operators Expressions  Operators and operands can be used to create more complex expressions Operand  Variables and literals contained in an expression Operators  Symbols used in expressions to manipulate operands Example:  myNumber = 100;

43 Introduction to JavaScript 243

44 Introduction to JavaScript 244 Expressions and Operators Operators  Can be binary or unary Binary  Requires an operand both before (left operand) and after (right operand) the operator  e.g.,  myNumber = 100; Unary  Requires a single operand either before or after the operator  e.g.,  myNumber++

45 Introduction to JavaScript 245 Expressions and Operators Arithmetic Operators  Used to perform mathematical calculations  Comprised of both binary and unary operators  Note: Addition operator (+), when used on strings concatenates the operands (operator overloading)

46 Introduction to JavaScript 246 Expressions and Operators Arithmetic Operators  Converting strings to integers: Reference: page 165 of JavaScript, the Definitive Guide.  Can use the Number() built-in function: var number = Number(string_value); only works with base-10 numbers, does not allow any non-space characters to appear in the string following the number

47 Introduction to JavaScript 247 Expressions and Operators Arithmetic Operators  Can use the parseInt() built-in function: var number = parseInt(“3 blind mice”) ; places the integer 3 into the var number only works with any base number, converts any number at the beginning of a string, ignores any non-number characters at the end.

48 Introduction to JavaScript 248 Expressions and Operators Arithmetic Operators  Can use the parseFloat() built-in function: var number = parseFloat(“3.12 blind mice”) ; places the value 3.12 into the number variable works with both integers and floating point numbers.

49 Introduction to JavaScript 249 Expressions and Operators Precision: You can adjust the number of digits a number has with number.toPrecision() var n = 12345.6789 n.toPrecision(1)// returns 1e+4 n.toPrecision(3)// returns 1.23e+4 n.toPrecision(5)// returns 12346: note rounding n.toPrecision(7)// returns 12345.67 n.toPrecision(10)// returns 12345.67890: note added zero

50 Introduction to JavaScript 250 Expressions and Operators Rounding: You can adjust a number by rounding with Math.round(theNum); Rounds a float number to nearest integer (.5 goes up). var n = 12345.6789 theNum = Math.round(n); // theNum now contains 12346

51 Introduction to JavaScript 251

52 Introduction to JavaScript 252 Expressions and Operators Examples:  numInPrompt.html numInPrompt.html  simple expressions folder ArithmeticExamples.html BirthInfo.html ImprovedProgram.html

53 Introduction to JavaScript 253 Expressions and Operators Arithmetic Operators  Unary operators Prefix operator  Placed before the operand ++count  Value returned after operation Postfix operator  Placed after the operand count++  Value returned before operation

54 Introduction to JavaScript 254 Expressions and Operators Assignment Operators  Used for assigning a value to a variable  Basic assignment operator (=) Assign initial value to new variable Assign a new value to an existing variable  NaN Not a Number Returned when a mathematical expression does not result in a numerical value

55 Introduction to JavaScript 255

56 Introduction to JavaScript 256

57 Introduction to JavaScript 257 Expressions and Operators Comparison Operators  Used to compare two operands for equality and if one numeric value is greater than another  Can use number or string values as operands

58 Introduction to JavaScript 258

59 Introduction to JavaScript 259 Expressions and Operators Comparison Operators  Conditional operator Executes one of two expressions, based on the results of a conditional expression Syntax  cond_expression ? expression1 : expression2; If con_expression = true  expression1 executes If con_expression = false  expression2 executes

60 Introduction to JavaScript 260 Expressions and Operators Logical Operators  Used for comparing two Boolean operands for equality  Comparison returns a Boolean value  Comprised of both binary and unary operators

61 Introduction to JavaScript 261

62 Introduction to JavaScript 262 Logical Operators Examples:  BooleanVariables.html BooleanVariables.html  LogicalExamples.html LogicalExamples.html

63 Introduction to JavaScript 263 Expressions and Operators Working with Strings  JavaScript has two operators that can be used with Strings to combine two strings Concatenation operator (+)  var oneString = “one”;  var anotherString = oneString + “, two, three, …”; Assignment operator (+=)  var oneString = “one”;  oneString += “, two, three, …”;

64 Introduction to JavaScript 264 Expressions and Operators String Object  Literal strings and string variables in JavaScript are represented by a String object  The String object contains methods for manipulating text strings

65 Introduction to JavaScript 265 Expressions and Operators String Object  length property Returns the number of characters in a string  Parsing Act of extracting characters or substrings from a larger string

66 Introduction to JavaScript 266 Expressions and Operators String Object  Parsing using the split() built-in function Reference: Javascript: the Definitive Guide, p 529. stringVariable.split(delimiter). Returns an array of strings, created by splitting string into substrings at the boundaries specified by delimiter.

67 Introduction to JavaScript 267 Expressions and Operators String Object  Parsing using the split() built-in function. Example: var myVar = “John Barr”; var newVar = myVar.split(“ “); newVar contains [“John”, “Barr”]

68 Introduction to JavaScript 268 Expressions and Operators String Object  Parsing using the split() built-in function. Example: var myVar = “red;blue;green;yellow”; var newVar = myVar.split(“;“); newVar contains [“red”, “blue”.”green”,”yellow”]

69 Introduction to JavaScript 269 Expressions and Operators Example:  StringExamples.html StringExamples.html

70 Introduction to JavaScript 270 Expressions and Operators Operator Precedence  Order of priority in which operations in an expression are evaluated  Expressions are evaluated On a left-to-right basis With the highest priority precedence evaluated first

71 Introduction to JavaScript 271 Expressions and Operators Operator Precedence  Parentheses/brackets/dot (( ) [ ].)  Negation/increment (! - ++ -- typeof void)  Multiplication/division/modulus (* / %)  Addition/subtraction (+ -)  Comparison ( >=)  Equality (== !=)  Logical AND (&&)  Logical OR (||)  Assignment operators (= += -= *= /= %=)  Comma (,)

72 Introduction to JavaScript 272 Decision Making Statements if statements if…else statements Nested if statements switch statements

73 Introduction to JavaScript 273 Decision Making  Process of determining the order in which statements execute in a program AKA – flow control  Decision-Making Structures Special type of JavaScript statements used for making decisions

74 Introduction to JavaScript 274 Decision Making if Statements  Used to execute specific programming code if the evaluation of a conditional expression returns a value of true “Do this or don’t do this”  Syntax (3 primary parts) if (conditional_expression) { statement(s); }

75 Introduction to JavaScript 275 Decision Making if Statements  Operation If the conditional expression is true, the statement(s) is/are executed Control then continues to subsequent code  Command block Multiple statements contained within a set of braces (require curly braces)

76 Introduction to JavaScript 276

77 Introduction to JavaScript 277

78 Introduction to JavaScript 278

79 Introduction to JavaScript 279 Decision Making if Statements  Conditional Expression Can consist of:  Comparison operators  Logical operators  Combination of the two Must resolve to Boolean value

80 Introduction to JavaScript 280 Decision Making if…else Statements  Used to execute one set of code if the evaluation of a conditional expression returns a value of true, otherwise executes another set of code “Do this or do something else”  Syntax if (conditional_expression) { statement(s); } else { statement(s); }

81 Introduction to JavaScript 281

82 Introduction to JavaScript 282 Decision Making Nested if and if…else Statements  Nested statements Statements contained within other statements  Syntax (variable) if (conditional_expression) { statement(s); if (conditional_expression) { statement(s); } } else { statement(s); }

83 Introduction to JavaScript 283

84 Introduction to JavaScript 284

85 Introduction to JavaScript 285 Decision Making switch Statements  Controls program flow by executing a specific set of statements, depending on the value of an expression  Syntax switch (expression) { case label1: statement(s); break; case label2: statement(s); break; default: statement(s); }

86 Introduction to JavaScript 286 Decision Making switch Statements  Case labels Identify specific code segments Can use a variety of data types as case labels  Break statement Used to exit switch statements  Default label Contains statements that execute when the condition expression doesn’t match any of the case labels

87 Introduction to JavaScript 287

88 Introduction to JavaScript 288 Repetition Statements while statements do…while statements for statements for…in statements with statements continue statements

89 Introduction to JavaScript 289 Repetition The if, if…else and switch statements select only a single branch of code to execute, then continue to the statement that follows  Loop statements Repeatedly execute a statement or a series of statements while a specific is true or until a specific condition becomes true

90 Introduction to JavaScript 290 Repetition while Statements  Used for repeating a statement or a series of statements as long as a given conditional expression evaluates to true Typically uses a counter to keep track of iteration  Syntax while (conditional_expression) { statement(s); }

91 Introduction to JavaScript 291 Repetition while Statements  Example: var count = 1; while (count <= 5) { document.writeln(count); ++count; } document.writeln(“You have printed 5 numbers.”);

92 Introduction to JavaScript 292

93 Introduction to JavaScript 293 Repetition while Statements  Example: var count = 10; while (count > 0) { document.writeln(count); --count; } document.writeln(“We have liftoff.”);

94 Introduction to JavaScript 294

95 Introduction to JavaScript 295 Repetition while Statements  Example: var count = 1; while (count <= 100) { document.writeln(count); count *= 2; }

96 Introduction to JavaScript 296

97 Introduction to JavaScript 297 Repetition while Statements  Infinite loop A situation in which a loop statement never ends because the conditional expression is never updated or is never false  Need to include code within the body of the while statement that changes some part of the conditional expression  Should also include code that monitors the conditional expression

98 Introduction to JavaScript 298 Repetition do…while Statements  Executes a statement or statements once, then repeats the execution as long as a given conditional expression evaluates to true “Do once, then test to see if it is done again”  Syntax do { statement(s); } while (conditional_expression) ;

99 Introduction to JavaScript 299

100 Introduction to JavaScript 2100

101 Introduction to JavaScript 2101 Repetition for Statements  Used for repeating a statement or series of statements as long as a given conditional expression evaluates to true “Do for a prescribed number of iterations”  Syntax for (initialization_expression; condition; update_statement) { statement(s); }

102 Introduction to JavaScript 2102 Repetition for Statements  Steps in processing a for loop Initialization expression is started  Only occurs once, when loop is first encountered Evaluate condition  If condition == true  execute loop body, go to next step  If condition == false  for statement ends Execute update statement  Then return to condition evaluation

103 Introduction to JavaScript 2103

104 Introduction to JavaScript 2104

105 Introduction to JavaScript 2105

106 Introduction to JavaScript 2106 Repetition break Statements  Stop executing the looping statement continue Statements  Halts a looping statement and restarts the loop with a new iteration

107 Introduction to JavaScript 2107

108 Introduction to JavaScript 2108

109 Introduction to JavaScript 2109


Download ppt "Introduction to JavaScript 21 Introduction to Programming the WWW I CMSC 10100-1 Winter 2004 Lecture 15."

Similar presentations


Ads by Google