Java Script Language Fundamentals About Java Script n

Java. Script Language Fundamentals

About Java. Script n Java. Script is not Java, or even related to Java n n Statements in Java. Script resemble statements in Java, because both languages borrowed heavily from the C language n n n Java. Script should be fairly easy for Java programmers to learn However, Java. Script is a complete, full-featured, complex language Java. Script is seldom used to write complete “programs” n n n The original name for Java. Script was “Live. Script” The name was changed when Java became popular Now that Microsoft no longer likes Java, its name for their Java. Script dialect is “Active Script” Instead, small bits of Java. Script are used to add functionality to HTML pages Java. Script is often used in conjunction with HTML “forms” Java. Script is reasonably platform-independent 2

Using Java. Script in a browser n Java. Script code is included within <script> tags: n n <script type="text/javascript"> document. write("<h 1>Hello World!</h 1>") ; </script> Notes: n n n The type attribute is to allow you to use other scripting languages (but Java. Script is the default) This simple code does the same thing as just putting <h 1>Hello World!</h 1> in the same place in the HTML document The semicolon at the end of the Java. Script statement is optional n n n The end of line marks the end of the statement, if the line can be interpreted as a complete statement You can use semicolons to separate statements on the same line It’s probably a good idea to keep using semicolons 3

Java. Script isn’t always available n Some old browsers do not recognize script tags n n n These browsers will ignore the script tags but will display the included Java. Script To get old browsers to ignore the whole thing, use: <script type="text/javascript"> <!-document. write("Hello World!") //--> </script> The <!-- introduces an HTML comment To get Java. Script to ignore the HTML close comment, -->, the // starts a Java. Script comment, which extends to the end of the line Some users turn off Java. Script n Use the <noscript>message</noscript> to display a message in place of whatever the Java. Script would put there 4

Example n John Smith's email: <script language=javascript> <!-var name = "smithj" var host 1 = "seas. up" var host 2 = "enn. edu" var addr = document. write("<a href=mai" + "lto: " + name + "@ " + host 1 + host 2 + "? subject=CIT 597: " + ">" + "John Smith" + "</a>") //--> </script> <noscript> smithj at seas </noscript> 5

Where to put Java. Script n Java. Script can be put in the <head> or in the <body> of an HTML document n n n Java. Script functions can be put in a separate. js file n n n Java. Script functions should be defined in the <head> n This ensures that the function is loaded before it is needed Java. Script in the <body> will be executed as the page loads <script src="my. Java. Script. File. js"></script> Put this in the <head> An external. js file lets you use the same Java. Script on multiple HTML pages The external. js file cannot itself contain a <script> tag Java. Script can be put in an HTML form object, such as a button n This Java. Script will be executed when the form object is used 6

Primitive data types n Java. Script has three “primitive” types: number, string, and boolean, and two special values, null and undefined n n Everything else is an object Numbers are always stored as floating-point values n n Hexadecimal numbers begin with 0 x Some platforms treat 0123 as octal, others treat it as decimal n n Strings may be enclosed in single quotes or double quotes n n Since you can’t be sure, avoid octal altogether! Strings can contains n (newline), " (double quote), etc. Booleans are either true or false n 0, "0", empty strings, undefined, null, and Na. N are false , other values are true 7

Variables n Variables can be declared with a var statement: n n n There are only two scopes: local and global n n n var pi = 3. 1416, x, y, name = "Dr. Dave" ; Variables names must begin with a letter or underscore Variable names are case-sensitive Variables are untyped (they can hold values of any type) Variables declared within a function are local to that function (accessible only within that function) Variables declared outside a function are global (accessible from anywhere on the page) Variables can also be declared implicitly, simply by assigning a value to them n Implicitly declared variables are always global 8

Operators, I n n n Because most Java. Script syntax is borrowed from C (and is therefore just like Java), we’ll go through it quickly Arithmetic operators (all numbers are floating-point): + * / % ++ -Comparison operators: < <= == != >= > Logical operators: && || ! (&& and || are short-circuit operators) Bitwise operators: & | ^ ~ << >> >>> Assignment operators: += -= *= /= %= <<= >>>= &= ^= |= 9

Operators, II n n n String operator: + The conditional operator: condition ? value_if_true : value_if_false Special equality tests: n n n == and != try to convert their operands to the same type before performing the test Not in C or Java: === and !== consider their operands unequal if they are of different types Additional operators (to be discussed): new typeof void delete 10

Comments n Comments are as in C or Java: n n n Between // and the end of the line Between /* and */ Java’s javadoc comments, /**. . . */, are treated just the same as /*. . . */ comments; they have no special meaning in Java. Script 11

Statements, I n Most Java. Script statements are also borrowed from C n n Assignment: greeting = "Hello, " + name; Compound statement: { statement; . . . ; statement } If statements: if (condition) statement; else statement; Familiar loop statements: while (condition) statement; do statement while (condition); for (initialization; condition; increment) statement; 12

Statements, II n The switch statement: switch (expression) { case label : statement; break; . . . default : statement; } n Other familiar statements: n n n break; continue; The empty statement, as in ; ; or { } 13

Java. Script is not Java n By now you should have realized that you already know a great deal of Java. Script n n Java. Script has some features that resemble features in Java: n n n So far we have talked about things that are the same as in Java. Script has Objects and primitive data types Java. Script has qualified names; for example, document. write("Hello World"); Java. Script has Events and event handlers Exception handling in Java. Script is almost the same as in Java. Script has some features unlike anything in Java: n n n Variable names are untyped: the type of a variable depends on the value it is currently holding Objects and arrays are defined in quite a different way Java. Script has with statements and a new kind of for statement 14

Exception handling, I n n Exception handling in Java. Script is almost the same as in Java throw expression creates and throws an exception n n The expression is the value of the exception, and can be of any type (often, it's a literal String) try { statements to try } catch (e) { // Notice: no type declaration for e exception handling statements } finally { // optional, as usual code that is always executed } n With this form, there is only one catch clause 15

Exception handling, II n n try { statements to try } catch (e if test 1) { exception handling for the case that test 1 is true } catch (e if test 2) { exception handling for when test 1 is false and test 2 is true } catch (e) { exception handling for when both test 1 and test 2 are false } finally { // optional, as usual code that is always executed } Typically, the test would be something like e == "Invalid. Name. Exception” but it could be any kind of test 16

Object literals n In Java, classes describe objects, and all objects of that class have exactly the same fields and methods n n n Java. Script objects are more flexible than Java objects Java. Script has object literals, written with this syntax: n { name 1 : value 1 , . . . , name. N : value. N } Example (from Netscape’s documentation): n n car = {my. Car: "Saturn", 7: "Mazda", get. Car: Car. Types("Honda"), special: Sales} n The fields are my. Car, get. Car, 7 (this is a legal field name) , and special n "Saturn" and "Mazda" are Strings n Car. Types is a function call n Sales is a variable that was defined earlier Example use: document. write("I own a " + car. my. Car); 17

Three ways to create an object n You can use an object literal: n n You can use new to create a “blank” object, and add fields to it later: n n var course = { number: "CIT 597", teacher: "Dr. Dave" } var course = new Object(); course. number = "CIT 597"; course. teacher = "Dr. Dave"; You can write and use a constructor: n n function Course(n, t) { // functions should be defined in <head> this. number = n; // keyword "this" is required, not optional this. teacher = t; } var course = new Course("CIT 597", "Dr. Dave"); 18

Array literals n Java. Script has array literals, written with brackets and commas n n n Example: color = ["red", "yellow", "green", "blue"]; Arrays are zero-based: color[0] is "red" If you put two commas in a row, the array has an “empty” element in that location n Example: color = ["red", , , "green", "blue"]; n n color has 5 elements However, a single comma at the end is ignored n Example: color = ["red", , , "green", "blue”, ]; still has 5 elements 19

Four ways to create an array n You can use an array literal: var colors = ["red", "green", "blue"]; n You can use new Array() to create an empty array: n n n You can use new Array(n) with a single numeric argument to create an array of that size n n var colors = new Array(); You can add elements to the array later: colors[0] = "red"; colors[2] = "blue"; colors[1]="green"; var colors = new Array(3); You can use new Array(…) with two or more arguments to create an array containing those values: n var colors = new Array("red", "green", "blue"); 20

The length of an array n n n If my. Array is an array, its length is given by my. Array. length Array length can be changed by assignment beyond the current length n Example: var my. Array = new Array(5); my. Array[10] = 3; Arrays are sparse, that is, space is only allocated for elements that have been assigned a value n n n Example: my. Array[50000] = 3; is perfectly OK But indices must be between 0 and 232 -1 As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: my. Array[5][3] 21

Arrays and objects n n Arrays are objects car = { my. Car: "Saturn", 7: "Mazda" } n n car[7] is the same as car. 7 car. my. Car is the same as car["my. Car"] If you know the name of a property, you can use dot notation: car. my. Car If you don’t know the name of a property, but you have it in a variable (or can compute it), you must use array notation: car["my" + "Car"] 22

Array functions n If my. Array is an array, n n n my. Array. sort() sorts the array alphabetically my. Array. sort(function(a, b) { return a - b; }) sorts numerically my. Array. reverse() reverses the array elements my. Array. push(…) adds any number of new elements to the end of the array, and increases the array’s length my. Array. pop() removes and returns the last element of the array, and decrements the array’s length my. Array. to. String() returns a string containing the values of the array elements, separated by commas (but not enclosed in brackets) 23

The for…in loop n n This is similar to Java’s for(type var : collection) loop You can loop through the properties of an object with for (variable in object) statement; n n n Example: for (var prop in course) { document. write(prop + ": " + course[prop]); } Possible output: teacher: Dr. Dave number: CIT 597 The properties are accessed in an undefined order If you add or delete properties of the object within the loop, it is undefined whether the loop will visit those properties Arrays are objects; applied to an array, for…in will visit the “properties” 0, 1, 2, … Notice that course["teacher"] is equivalent to course. teacher n You must use brackets if the property name is in a variable 24

More about the for. . . in loop n The for. . . in loop does not loop through all properties of an object n n n Built-in methods, and many built-in properties, are flagged as nonenumerable All built-in properties of functions are nonenumerable There are lots of little surprises like this in Java. Script 25

The with statement n with (object) statement ; uses the object as the default prefix for variables in the statement n n For example, the following are equivalent: n n n If the accessed field doesn’t exist, the prefix isn’t used with (document. my. Form) { result. value = compute(my. Input. value) ; } document. my. Form. result. value = compute(document. my. Form. my. Input. value); The with statement is useful when you are doing a lot of manipulation on the same object n The with statement can be confusing, and should be used with care 26

Functions n n Functions should be defined in the <head> of an HTML page, to ensure that they are loaded first The syntax for defining a function is: function name(arg 1, …, arg. N) { statements } n n The function may contain return value; statements Any variables declared within the function are local to it The syntax for calling a function is just name(arg 1, …, arg. N) Simple parameters are passed by value, objects are passed by reference 27

Regular expressions n A regular expression can be written in either of two ways: n n Within slashes, such as re = /ab+c/ With a constructor, such as re = new Reg. Exp("ab+c") Regular expressions are almost the same as in Perl or Java (only a few unusual features are missing) string. match(regexp) searches string for an occurrence of regexp n n n It returns null if nothing is found If regexp has the g (global search) flag set, match returns an array of matched substrings If g is not set, match returns an array whose 0 th element is the matched text, extra elements are the parenthesized subexpressions, and the index property is the start position of the matched substring 28

Warnings n Java. Script is a big, complex language n n Java. Script is not totally platform independent n n n We’ve only scratched the surface It’s easy to get started in Java. Script, but if you need to use it heavily, plan to invest time in learning it well Write and test your programs a little bit at a time Expect different browsers to behave differently Write and test your programs a little bit at a time Browsers aren’t designed to report errors n n Don’t expect to get any helpful error messages Write and test your programs a little bit at a time 29

Evaluation (i. e. , Dave’s opinion) n n Java. Script, like Java, is in the C family of languages Java. Script has lots of convenience features n n n Java. Script is designed for programming in the small, not for large programs n n Global variables Not having to declare variables at all Untyped variables Easy modification of objects Many features, such as global variables, are bad news for large programs My experience is that Java. Script is very nice if you use it for the purposes that its designers expected, but very ugly if you try to use it in non-routine ways 30

The End 31
- Slides: 31