JavaScript

• Interpreted with OO capabilities • Core syntax resembles , C++ and JAVA • However: – Loosely typed - variables do not need to have a type specified JavaScript Elements – JS Objects are more like hash tables or associative arrays than they are like structs (C) or objects (C++, Java) – OO inheritance is prototype-based – Draws inspiration from in regular expressions and array- handling features

2

Overview of JavaScript Overview of JavaScript • Originally developed by Netscape, as LiveScript • JavaScript can be used to: – replace some of what is typically done with applets (except • Became a joint venture of Netscape and Sun in graphics) 1995, renamed JavaScript – replace some of what is done with CGI - namely server-side • Now standardized by the European Computer programming (but no file operations or networking) Manufacturers Association as ECMA-262 (also • User interactions through forms are easy ISO 16262) • The Document Object Model makes it possible to support dynamic HTML documents with JavaScript • We’ll call collections of JavaScript code scripts, – Much of what we will do with JavaScript is event-driven not programs computation

http://www.ecma-international.org/publications/standards/Ecma-262.htm 3 4 Object Orientation and JavaScript JavaScript and JAVA

• JavaScript is NOT an object-oriented programming • JavaScript and Java are only related through syntax language • JAVA is strongly typed - types are known at compile time – Does not support class-based inheritance - cannot support and operand types (τύποι τελεστέων) are checked for polymorphism compatibility – Has prototype-based inheritance, which is much different • Variables in JavaScript are dynamically typed • JavaScript objects are collections of properties, which are – Compile-time type checking impossible like the members of classes in Java and C++ • Objects in JAVA are static: • JavaScript has primitives for simple types – their collection of data members and methods is fixed at • The root object in JavaScript is Object – all objects are compile time derived from Object • JavaScript objects are dynamic: – members of an object can change during execution • All JavaScript objects are accessed through references

5 6

Browsers and HTML/JavaScript Documents Implicit vs Explicit JavaScript • What happens when the browser encounters a JavaScript • Explicit embedding: script in a document? – Mixes two types of notation inside the same document (bad • Two approaches for embedding JavaScript in HTML for readability) documents: – Makes maintenance difficult - often different people manage – Explicit embedding (ρητή ενσωμάτωση) the HTML and the JavaScript – The head of an HTML document - for scripts that produce – Implicit embedding (υπόρρητη ενσωμάτωση) content only upon request or for those that react to user • These scripts contain function definitions and code associated with form elements – The body of an HTML document - for scripts that are to be interpreted just once, as they are found 7 8 JavaScript embedding JavaScript objects

• Scripts are usually hidden from browsers that • Objects are collections of properties: do not include JavaScript interpreters by putting – data properties (primitive values and references to objects) them in special comments: – method properties (methods) object. E.g. myCar.engine • This is also required by the HTML validator • Objects are dynamic collections of property-value pairs • Note that the comment closure is in a new line and – Properties are names is also a JS comment – Values are data values or functions • All functions are objects and are referenced through variables 9 10

JavaScript objects Client-Side JavaScript • An object can represent: Unordered collection of named values – Ordered collection of numbered values: array – An entity that has executable code associated with it: This is a test on Javascript and HTML function

The Table of factorials

• Because these three kinds of objects behave differently, Error 11 12 General Syntactic Characteristics Primitives, Operations, Expressions

• Identifier: simply a name, used to: • Boolean values are true and false – name variables and functions • The only Null value is – provide labels for certain loops – syntax same as Java: • The only Undefined value is undefined • begin with a letter or underscore, followed by any number of letters, • JavaScript is dynamically typed underscores, and digits – • case sensitive any variable can be used for anything (primitive value or reference to any object) • Comments: both // and /* … */ – The interpreter determines the type of a particular occurrence of a variable (values do have type) • Variables can be either implicitly or explicitly declared

var sum = 0, today = "Monday", flag = false;

13 14

Primitives, Operations, Expressions Primitives, Operations, Expressions

• Numeric operators - ++, --, +, -, *, /, % • Primitives, Operations, & Expressions (continued) – – All operations are in double precision String catenation operator : + – Coercions (implicit type conversions) – Same precedence and associativity as Java – Catenation coerces numbers to strings • The Math Object provides floor, round, max, min, trig – Numeric operators (other than +) coerce strings to numbers (if either operand of functions, etc. e.g., Math.cos(x) + is a string, it is assumed to be catenation) – Conversions from strings to numbers that do not work return NaN • The Number Object collects useful properties that have constant • Explicit conversions values – Use the String and Number constructors – Some useful properties: – Use toString method of numbers – • MAX_VALUE, MIN_VALUE, NaN, POSITIVE_INFINITY, NEGATIVE_INFINITY, Use parseInt and parseFloat on strings PI • String properties & methods: • e.g., Number.MAX_VALUE – length e.g., var len = str1.length; (a property) • An arithmetic operation that creates overflow returns NaN – charAt(position) e.g., str.charAt(3) – NaN is not 55 to any number, not even itself – indexOf(string) e.g., str.indexOf('B') – Test for it with isNaN(x) – substring(from, to) e.g., str.substring(1, 3) – toLowerCase() e.g., str.toLowerCase() • Number object has the method, toString 15 16 Primitives, Operations, Expressions Screen output and keyboard input

• The typeof operator • JavaScript models the HTML document inside which a script – Returns "number", "string", or "boolean" for Number, String, or Boolean, "undefined" for Undefined, "function" for functions, and "object" for is embedded, as a Document object objects and for NULL • The model for the browser display window is the Window • Assignment statements – just like C++ and Java object • The Date Object – The Window object has two properties, document and window, – Create one with the Date constructor (no params): var today = new Date(); which refer to the Document and Window objects, respectively – Local time methods of Date: (window is self-referential) • toLocaleString – returns a string of the date – The Document object has a method, write, which dynamically • getDate – returns the day of the month creates content • getMonth – returns the month of the year (0 – 11) • getDay – returns the day of the week (0 – 6) • Its parameter is a string, often catenated from parts, some of • getFullYear – returns the year which are variables e.g., • getTime – returns the number of milliseconds since January 1, 1970 document.write("Answer: " + result + "
"); • getMinutes – returns the minutes (0 – 59) • The parameter is sent to the browser, so it can be anything that can • getMilliseconds – returns the millisecond (0 – 999) appear in an HTML document (
, but not \n) 17 18

Screen output

• The Window object has three methods for creating dialog boxes: – alert, confirm, and prompt Window • alert("Hej! \n"); – Parameter is plain text, not HTML – Opens a dialog box which displays the parameter string and an OK button – It waits for the user to press the OK button • confirm("Do you want to continue?"); Document – Opens a dialog box and displays the parameter and two buttons, OK and Cancel – Returns a Boolean value, depending on which button was pressed (it waits for one) • prompt("What is your name?", ""); – Opens a dialog box and displays its string parameter, along with a text box and two buttons, OK and Cancel – The second parameter is for a default response if the user presses OK without typing a response in the text box (waits for OK)

19 20 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 24 // roots.js Control Statements // Compute the real roots of a given quadratic // equation. If the roots are imaginary, this script • Similar to C, Java, and C++ // displays NaN, because that is what results from – // taking the square root of a negative number Compound statements are delimited by braces, but compound statements are not blocks // Get the coefficients of the equation from the user • Control expressions – three kinds var a = prompt("What is the value of 'a'? \n", ""); – Primitive values var b = prompt("What is the value of 'b'? \n", ""); • If it is a string, it is true unless it is empty or "0" var c = prompt("What is the value of 'c'? \n", ""); • If it is a number, it is true unless it is zero // Compute the square root and denominator of the result – Relational Expressions • The usual six: 55, !5, <, >, <5, >5 var root_part = Math.sqrt(b * b - 4.0 * a * c); • Operands are coerced if necessary var denom = 2.0 * a; • If one is string and one is number: attempts to convert string to num // Compute and display the two roots • If one is Boolean and other is not, the Boolean operand is coerced to a number (1 or 0) var root1 = (-b + root_part) / denom; • The unusual two: === and !==; Same as 55 and !5, except that no var root2 = (-b - root_part) / denom; coercions are done (operands must be identical) document.write("The first root is: ", root1, "
"); • E.g. ‘3’ 555 3 evaluates to false document.write("The second root is: ", root2, "
"); • Comparisons of references to objects are not useful (addresses are compared, not values) 25 26

Control Statements Control Statements

• Compound Expressions • Switch – The usual operators: &&, ||, and ! switch (expression) { – The Boolean object has a method, toString, to allow them to case value_1: be printed (true or false) // value_1 statements – If a Boolean object is used in a conditional expression, it is false case value_2: only if it is null or undefined // value_2 statements … • Selection Statements [default: – The usual if-then-else (clauses can be either single statements or // default statements] compound statements) }

• The statements can be either statement sequences or compound statements • The control expression can be a number, a string, or a Boolean – Different cases can have values of different types

27 28 // borders2.js Document.write(" 2008 NFL Divisional", " Winners "); // An example of a switch statement for table border document.write("", "", // size selection " American Conference ", " National Conference ", var bordersize; "", bordersize = prompt("Select a table border size \n" + "", "0 (no border) \n" + " East ", "1 (1 pixel border) \n" + " Miami Dolphins ", "4 (4 pixel border) \n" + " New York Giants ", "", "8 (8 pixel border) \n"); "", " North ", switch (bordersize) { " Pittsburgh Steelers ", case "0": document.write("

"); "", break; "", case "1": document.write("
Minnesota Vikings
"); "", "", break; "", case "4": document.write("
West San Diego Chargers
"); "", break; "", case "8": document.write("
Arizona Cardinals
"); "", break; "", default: document.write("Error - invalid choice: ", "", bordersize, "
"); "", (ctd’) "", } 29 "
South Tennessee Titans Carolina Panthers
"); 30 Control Statements

• Loop statements

while (control_expression) statement or cmpnd

for (init; control; increment) stmt or cmpnd

– init can have declarations, but the scope of such variables is the whole script

do statement or compound while (control_expression)

31 32 Object creation and Modification Object properties • Objects are often created with a new expression, which • Created by assigning a value to a property’s name must include a call to a constructor my_car.make = “Ford”; my_car.model = “Contour”; • new creates a blank object - one with no properties my_car.engine = new Object(); -- Object nesting – JavaScript objects do not have types my_car.engine.config = “V6”; – The constructor both creates and initialises object properties. my_car.engine.hp = 200; E.g., the following command creates an object with some • Object properties are not variables - they are just inherited method properties, but no data properties: names of values, used with object variables to access var my_car = new Object(); property values. E.g.: – The following command creates a blank object and assigns two document.write(my_car.engine); properties to the object: • The number of properties in a JavaScript object is var my_car = {make: “Ford”, model: “Contour”); dynamic - at any time during interpretation, properties can be added to or deleted from an object. delete(my_car.model); 33 34

Accessing object properties Arrays • A property can be accessed the same way it is assigned a • Objects with some special functionality – Array elements can be primitive values or references to other objects value, namely with the object-dot-property notation – Length is dynamic - the length property stores the length • Property names can be accessed also as if they were • Array objects can be created in two ways, with new, or by assigning elements of an array: an array literal – for (identifier in object) var myList = new Array(24, "bread", true); – var myList2 = [24, "bread", true]; statement or compound – var myList3 = new Array(24);

for (var prop in my_car) • The length of an array is the highest subscript to which an element document.write(“Name: ”, prop, “; Value:”, has been assigned, plus 1 my_car[prop] + "
"); – myList[122] = "bitsy"; // length is 123 • Because the length property is writeable, you can set it to make the array any length you like, as in: – myList.length = 150; • Assigning a value to an element that does not exist creates that

35 element 36 Arrays (continued) Variables

• Array methods: • Variables can be implicitly or explicitly declared: – join – converts all elements of an array to strings and concatenates – Variables declared with a var statement are explicitly declared. – them into a single string e.g. Other variables are implicit. var listStr = list.join(", "); • Scope of a variable (πεδίο εμβέλειας): the range of statements – reverse over which the variable is visible. – sort – e.g., names.sort(); • When JS is embedded in an HTML document, the scope of a • Coerces elements to strings and puts them in alphabetical order variable is the range of lines of the document over which the – concat – catenates its actual parameters to the end of the array object e.g., newList = list.concat(47, 26); variable is visible. – slice - returns the selected elements in an array, as a new array • Implicitly declared variables have global scope, i.e. they are object visible in the entire HTML document or JS file. • listPart = list.slice(2, 5); – • listPart2 = list.slice(2); This is true also for implicit variables defined inside a – toString: Coerce elements to strings, if necessary, and catenate function definition. them together, separated by commas (exactly like join(", ")) • Variables explicitly declared inside a function have local scope. – push, pop, unshift, and shift 37 38

Functions Function definitions function function_name([formal_parameters]) { • JS interpreter has to see a function definition before it sees -- body – a function call. } – Function definitions are placed in the head of an HTML • Return value is the parameter of return document (either implicitly or explicitly) – If there is no return, or if the end of the function is reached, undefined is – returned Normally (not always) calls to functions appear in the – If return has no parameter, undefined is returned document body • Functions are objects, so variables that reference them can be treated as other object references: – can be passed as parameters – be assigned to other variables – be the elements of an array – can be properties to other objects, in which case they act as methods

function fun() { document.write(“Hello world
;} ref_fun = fun; // ref_fun refers to the fun object fun(); // a call to fun

ref_fun(); /* Another call to fun */ 39 40 Parameter passing function params(a, b) { • Parameters are passed by value, like in C, C++ and Java document.write("Function params was passed ", • When a reference variable is passed (pointing to an object), the semantics are arguments.length, " parameter(s)
"); essentially pass-by-reference (we can change the object’s contents inside the document.write("Parameter values are:
"); function). for (var arg = 0; arg < arguments.length; arg++) • There is no type checking of parameters, nor is the number of parameters document.write(arguments[arg], "
"); checked (excess actual parameters are ignored, excess formal parameters are set to undefined) document.write("
"); • All parameters are sent through a property array, arguments, which has the } length property // A test driver for function params • There is no clean way to send a primitive by reference – One dirty way is to put the value in an array and send the array’s name params("Mozart"); function by10(a) { a[0] *= 10; params("Mozart", "Beethoven"); } params("Mozart", "Beethoven", "Tchaikowsky"); ... var listx = new Array(1); ... listx[0] = x; by10(listx); x = listx[0];

41 42

Functions as parameters

• To sort something other than strings into alphabetical order, write a function that performs the comparison and send it to the sort method • The comparison function must return a negative number, zero, or a positive number to indicate whether the order is ok, equal, or not function num_order(a, b) {return a - b;} • Now, we can sort an array named num_list with: num_list.sort(num_order);

43 44 function median(list) { list.sort(function (a, b) {return a - b;}); Constructors var list_len = list.length; • Used to create and initialize properties of newly created objects // Use the modulus operator to determine whether // the array's length is odd or even // Use Math.floor to truncate numbers function plane(newMake, newModel, newYear){ // Use Math.round to round numbers this.make = newMake; this.model = newModel; if ((list_len % 2) == 1) this.year = newYear; return list[Math.floor(list_len / 2)]; } else return Math.round((list[list_len / 2 - 1] + list[list_len/2])/2); myPlane = new plane("Cessna","Centurnian", "1970"); } // end of function median

// Test driver - Can also have method properties var my_list_1 = [8, 3, 9, 1, 4, 7]; var my_list_2 = [10, -2, 0, 5, 3, 1, 7]; function displayPlane() { var med = median(my_list_1); document.write("Make: ", this.make,"
"); document.write("Median of [", my_list_1, "] is: ", med, "
"); med = median(my_list_2); document.write("Model: ", this.model, "
"); document.write("Median of [", my_list_2, "] is: ", med, "
"); document.write("Year: ", this.year,"
"); } - Now add the following to the constructor: this.display = displayPlane; 45 46

Pattern Matching Pattern Matching search(pattern) • JavaScript provides two ways to do pattern matching: – Returns the position in the object string of the pattern – Using RegExp objects (position is relative to zero); returns -1 if it fails – Using methods on String objects var str = "Gluckenheimer"; • Both ways use the same type of regular expressions, var position = str.search(/n/); /* position is now 6 */ which are based on PERL • Character classes • Patterns sent as parameters to pattern-matching methods – Put a sequence of characters in brackets, and it defines a set are delimited with slashes: /RegExp/ of characters, any one of which matches: [abcd] • Simple patterns: two categories of characters in patterns: – Dashes can be used to specify spans of characters in a class: – normal characters (match themselves) [a-z] – meta characters (can have special meanings in patterns--do not match • A caret at the left end of a class definition means the themselves): \ | ( ) [ ] { } ^ $ * + ? . • A meta character is treated as a normal character if it is backslashed opposite [^0-9] – Period is a special meta character - it matches any character except newline 47 48 Pattern Matching Pattern Matching

• Abbreviations • Quantifiers (ποσοτικοποιητές) – {n} exactly n repetitions – {m,} at least m repetitions – {m, n} at least m but not more than n repetitions – * means zero or more repetitions, e.g., \d* means zero or more digits – + means one or more repetitions, e.g., \d+ means one or more digits – ? means zero or one, e.g., \d? means zero or one digit \d [0-9] a digit • Anchors: the pattern can be forced to match only at the left end with ^; at the end \D [^0-9] not a digit with $ e.g., \w [A-Za-z_0-9] a word character /^Lee/ matches "Lee Ann" but not "Mary Lee Ann" \W [^A-Za-z_0-9]not a word character /Lee Ann$/ matches "Mary Lee Ann", but not "Mary Lee Ann is nice" \s [ \r\t\n\f] a whitespace character • \S [^ \r\t\n\f] not a whitespace character Pattern modifiers – The i modifier tells the matcher to ignore the case of letters – /oak/i matches "OAK" and "Oak" – The x modifier tells the matcher to ignore whitespace and comments in the pattern (allows comments in patterns) • Parenthesised Substring Matches: Including parentheses in a regular expression pattern causes the corresponding sub-match to be remembered. – For example, /a(b)c/ matches the characters 'abc' and remembers 'b'.

49 50

Pattern Matching Methods of String Pattern Matching Methods of String

replace(pattern, string) match(pattern) • The most general pattern-matching method • Finds a substring that matches the pattern and replaces • Returns an array of results of the pattern-matching operation it with the string (g modifier can be used) – With the g modifier, it returns an array of the substrings that – The matched substrings are made available through the matched predefined variables $1, $2, and so on – Without the g modifier, first element of the returned array has the matched substring, the other elements have the matches of var str = "Some rabbits are rabid"; parenthesised parts of the pattern, if any str.replace(/rab/g, "tim"); var str = "My 3 kings beat your 2 aces"; var matches = str.match(/[ab]/g); str is now "Some timbits are timid" - matches is set to ["b", "a", "a"] $1 and $2 are both set to "rab"

51 52 function tst_phone_num(num) {

// Use a simple pattern to check the number of digits and the dash var ok = num.search(/^\d{3}-\d{4}$/);

if (ok == 0) return true; else return false;

} // end of function tst_phone_num

// A script to test tst_phone_num var tst = tst_phone_num("444-5432"); if (tst) document.write("444-5432 is a valid phone no
"); else document.write("Program error
"); tst = tst_phone_num("444-r432"); if (tst) document.write("Program error
"); else document.write("444-r432 is not a valid phone no
"); tst = tst_phone_num("44-1234"); if (tst) document.write("Program error
"); else document.write("44-1234 is not a valid phone no

53 54