11.08.05 Lecture Notes Some additional JavaScript notes, based on "JavaScript: The Definitive Guide" by David Flanagan (4th edition) (1) Literals: The following are all literals: number literals: 3 // the integer number 3 3.5 // the floating-point number 3.5 Try typing: javascript: typeof 3 javascript: typeof 3.5 string literals: "University of Delaware" // A string literal "103" // the number of this course _as a string_ 'Interactive Media' // another string literal Type typing: javascript: boolean literals true // a boolean literal false // another boolean literal [Note that usually "Boolean" is written with a capital B, but we follow the convention of lowercase, since that is the "type" of boolean variables in JavaScript] Other kinds of literal values null // a value indicating that "there is no object here" /CISC[0-9]+/ // a regular expression literal (for pattern matching) { size:14, topping:"cheese" } // an object literal [90, 100, 95, 87] // an array literal Except for /CISC[0-9]+/ which shows up as "function", all the rest show up as type "object". Info on regular expressions: http://www.sitepoint.com/print/expressions-javascript (2) Identifiers Identifiers in JavaScript are the names we give to things, including variables, functions, methods, and other kinds of "named things". e.g. var pizzaSize = 12; pizzaSize is an identifier function calculate() { document.gasForm.distance.value = document.gasForm.endOdom.value - document.gasForm.startOdom.value; } calculate is an identifier. Identifiers can contain letters, digits, the underscore character, and/or the dollar sign, and must not start with a digit. 4ever n westGrove4ever y iLoveYou y $money$money$money y 2Die4 n price of pizza n price_of_pizza y price.of.pizza n... this would be three separate identifiers separated with dot syntax (3) Data Types There are three "primitive" data types string: "Hi" '103' "Fred and Mary" "" number: 2 2.5 -9 0 boolean: true false There are also the values null undefined Then, there are also objects arrays And finally: functions As it turns out, arrays and functions are special types of objects, but it is often easier to think of them as something "different". There are also things called "classes" that represent special types of objects, including the Date class the RegExp class (regular expressions, used for pattern matching) the Error class (4) More on numbers (4.1) Integers Integers in JavaScript have a wide range: from -2 to the 53rd power to 2 to the 53rd power, which is larger than 9 "quadrillion" (a 9 with 15 zeros after it, or 9 million billion). -9,007,199,254,740,992 to 9,007,199,254,740,992 (though we would have to write that number without the commas if we were were writing it in JavaScript code.) According to Flanagan, "If you integer values larger than this "you may lose precision in trailing digits". Integers are typically written in base 10. If you want to write in base 16 (hex), put 0x at the start of the number, e.g. 0xFF00CC There is an ambiguity about numbers that start with a 0; some browsers treat them as decimal, while other treat them as octal, so avoid putting a 0 at the start of a number (e.g. don't write 0673 when you mean to write 673). (4.2) Floating point numbers Can be written with regular notation, e.g . 3.14 or using scientific notation by putting an "E" in the number, e.g. 6.022E23 which means 6.022 times 10 to the 23d power Not all floating point numbers can be represented exactly, so the JavaScript representation sometimes is "approximate". But usually, it is close enough. (4.3) Mathematical operations +, -, *, / work as expected For trig and other calculations, the "Math" class has methods to use: x = r * Math.cos(theta) ; disc = Math.sqrt(b*b - 4*a*c); For converting between bases, you can use the "toString" method. You pass in the base: var x = 65; var y = x.toString(2); // converts 65 to string "01000001" You can also do this on a numeric literal if you put it in parentheses: document.write( (65).toString(16) ); // writes "41" document.write( (255).toString(16) ); // writes "FF" (4.4) Extreme numbers Infinity NaN Number.MAX_VALUE Number.MIN_VALUE Number.NaN (must use isNaN() or isFinite() to test for this) Number.POSITIVE_INFINITY Number.NEGATIVE_INFINITY (5) More on strings Escape characters: \n newline \" double quote \' single quote \xFF the Latin-1 character represented by the hex digits FF \uFFFF the Unicode character represented by hex digits FFFF for example, \n is the same as \u000A We saw that we can print an E with an acute accent by using String.fromCharCode(201). Well, 201 in Hex is c9. We can also print an E with an acute accent by using "\u00c9". "\xC9" If s is a variable containing a string, e.g. var s = "UD"; var firstName = "William"; var lastName = "Conrad"; then s.length is the length of that string. so: s.length is 2 firstName.length is 7 lastName.length is 6 The charAt method returns the character at a given position. Positions are numbered starting from 0. So: s.charAt(0) is "U" s.charAt(1) is "D" firstName.charAt(firstName.length - 1) is the last character of firstName (i.e. "m") The substring method pulls out a portion of a string: firstName.substring(3,5) is "li" 3 is where I start, 5 means stop BEFORE you get to 5 (6) The boolean values true and false are sometimes treated as 1 and 0. (7) Functions: (7.1) Defining a simple function: function someSillyFunction() { var x = 3; window.alert("x = " + x); } Calling that function: someSillyFunction(); You can put the function call (1) inside a section, (2) in an eventHandler such as: ... (3) inside another function (7.2) Defining a function with parameters: Look at function in 11.08_page0.html function annoySeveralTimes(howManyTimes) { // the value of howManyTimes is passed in the function call var message; while (howManyTimes > 0) { howManyTimes --; message = "I'm annoying you.\n"; if (howManyTimes > 1) { message += "I'm going to annoy you " + howManyTimes + " more times."; } window.alert(message); } // end while } // end function Now you can use that function call with code like: annoySeveralTimes(1); // will only annoy once annoySeveralTimes(3); // will annoy three times annoySeveralTimes(0); // will call the function, but nothing will happen annoySeveralTimes(-3); // no different in effect from annoySeveralTimes(0); Function with parameters are more powerful and flexible than functions without parameters. (8) Variable declarations var x; or var y = 3; "declare" that x and y are variables. It is permitted to declare variables more than once. It is not required to declare a variable, but if you use a variable in a function and you DON'T declare it with "var", it becomes a "global" variable, and this means it can interfere with the operation of other functions. Declaring it with var makes it local, which means its effects are confined to that one function. So, always declare your variables with var! (9) Objects and Instances Objects are categorized into "classes". A specific object is an "instance" of some class. javascript: x = new Date(2005, 11, 25 ); x Sun Dec 25 2005 00:00:00 GMT-0500 (Eastern Standard Time) javascript: x = new Date(2005, 11, 25 ); typeof x object javascript:x = new Date(2005, 11, 25); x instanceof Date javascript:x = new Date(2005, 11, 25); x instanceof Object javascript: x = 3; typeof x number javascript: x = 3; x instanceof Object false javascript: x = new Number(3); x instanceof Number true javascript: x = new Number(3); x instanceof Object true (10) Creating new objects var myPizza = new Object(); // invokes a "constructor" // set attributes of the new object myPizza.topping = "Cheese"; myPizza.price = 9.99; myPizza.size = 14; Or: myPizza=new Object({size:14, price:9.99, topping:"cheese"}); Now look at 11.08_page1.html 11.08_page2.html 11.08_page3.html Note how you can iterate through a list of an object's properties.