Lecture 9b: JavaScript

What You Will Learn Today

  1. Use values, variables, literals and characters.
  2. Use operators and statements.
  3. Define and call functions.
  4. Use built-in objects (Array, Math, String and Date) and create new objects.
  5. Use event handlers to process events from form elements and other objects.
  6. Work with images and animations.

Values, Variables, Literals, Characters

Category Description of Syntax Example
values numbers, logical, strings, null, undefined 3.14, true/false, "Hello"
type
conversion
number + string returns string
string - number returns number
x = "Size " + 42 // returns "Size 42"
y = 12 + " eggs" // returns "12 eggs"
"37" - 7 // returns 30
"37" + 7 // returns 377
assignment assign a value to a variable x = 42
declaration use keyword var (to prevent runtime error)  var x = 42
conversion
to numbers
or strings
parseInt(str)
parseFloat(str)
String(number)
var age = parseInt(f.age.value)
var mass = parseFloat(f.mass.value)
s = String(Math.PI)
integer literals digits, sign, hexadecimal 42, -345, 0xFFF
floating point
literals
decimal point, scientific notation 3.1415, -3.1E12, .1e12, 2E-12
string literals enclose strings in quotes (single or double) "blah", 'blah', "1234", "one line \n another line"
array literal list of array values enclosed in brackets coffees = ["French Roast", "Columbian", "Kona"]
special or
escaped
characters
\ followed by the character: 
backspace, formfeed, newline, carriage return, 
tab, single quote, double quote, backslash
\b, \f, \n, \r, \t, \', \", \\

Operators

Category Description of Syntax Example
assignment
operators
= to assign a value to a variable
+=, -=, *=, /=, etc. are shorthand
x = y // assigns y to x
x += y // same as x = x + y
comparison
operators
equal, not equal, greater than, less than, ge, le x == y, x != y, x > y, x < y, x >= y, x <= y
arithmetic
operators
addition, subtraction, multiplication, division, 
increment, decrement, unary negation, modulus
1 + 2, 1 - 2, 1 * 2, 1 / 2, x++, y--, -x, x % y
logical operators and, or, not false && true // returns false
false || true // returns true
!true // returns false
string
operator
+ joins strings "my" + "string" // returns "mystring"
conditional
operator
condition ? val1 : val2 status = (age >= 18) ? "adult" : "minor"

Statements

Category Description of Syntax Example
statements ; // semicolon separates multiple statements on a line a = 10; b = 20; c = 30;
comments begin one-line comments with //
use /* and */ for multiple-line comments
// This is a single-line comment.
/* This is a multiple-line comment. It can be of any length, and can contain anything. */
conditional
if..else
if (condition) { statements1 }[else { statements2 }] if (name == "John") 
{ alert("Your name is John"); } 
else { alert("You are not John"); }
conditional
switch
switch (expression){
case label : statement; break;
case label : statement; break; ...
default : statement;}
switch (gender) { 
case "m": title="Sir"; break; 
case "f": title="Madam"; break; 
default: title="Sir or Madam";}
for loop for ([initialExpression]; [condition]; [incrementExpression])
{ statements}
fact = 1; for (i=2; i<=n; i++) fact *= i;
do..while do { statements } while (condition) do { i+=1; document.write(i);} while (i<5);
while while (condition) { statements } while (true) { alert("Hello") } // infinite loop

Functions

Category Description of Syntax Example
defining function name (arg1, arg2, ..., argn) { statements } function square (number) { return number * number; }
calling name(arg1, arg2, ..., argn) square(5) // returns 25
arguments functionName.arguments[i] or arguments[i] returns argument i
arguments.length returns number of arguments
function myConcat(separator) { result=""; 
for (var i=1; i<arguments.length; i++)
{ result += arguments[i] + separator }
return result; }

Objects

Category Description of Syntax Example
Array
object
arrayObjectName = new Array(arrayLength)
or Array(element0, element1, ..., elementN)
property: length
methods: concat, join, pop, push, reverse, shift, slice, splice, sort, unshift
myArray = new Array("Wind","Rain","Fire");
myArray[0] // returns "Wind"
myArray.pop() // removes and returns "Fire"
myArray.shift() // removes and returns "Wind"
myArray.length // returns 1
Math
object
property: PI
methods: abs, sin, cos, tan, asin, acos, atan, exp, log, ceil, floor, min, max, pow, round, sqrt
Math.PI is 3.141592...; Math.abs(-1) is 1;
Math.cos(0) is 1; Math.log(1) is 0;
Math.floor(3.1) is 3; Math.min(4,5) is 4;
Math.pow(2,3) is 8; Math.sqrt(16) is 4
String
object
property: length
HTML methods: anchor, link, big, bold, etc.
other methods: concat, indexOf, lastIndexOf, split, splice, substr, toLowerCase, toUpperCase
s1 = new String("Hello") //creates a String object
s1.length // returns 5
s1.bold() // returns <b>Hello</b>
s1.lastIndexOf("l") // returns 3
s1.toUpperCase() // returns "HELLO"
Date object object for displaying date and time today = new Date();
constructor objectName = new objectType ( param1 [,param2] ...[,paramN] ) myobject = new Car ("red", "fast", "sporty")
destructor delete objectName delete myobject
current object this[.propertyName] <input type="button" value="Do something to the form" onclick="myFunction(this.form)">
for..in for (variable in object) { statements } for (var i in obj) { result += obj_name + "." + i + " = " + obj[i] + "" }
with with (object){ statements} var a, x, y; var r=10; with (Math) { a = PI * r * r; x = r * cos(PI); y = r * sin(PI/2);}

Event Handlers

handler User event (action/trigger) Applies to Examples
onClick User clicks form element or link all buttons, checkboxes, links <input type="button" value="Calculate" onClick="compute(this.form)">
onChange User changes value of element text fields, textareas, select lists <input type="text" onChange="alert('Sorry, this value is read only.')">
onFocus User gives input focus to window or form element windows and all form elements <input type="text" onFocus="this.select()">
onBlur User removes input focus from window or form element windows and all form elements <input type="text" onBlur="updateValue(this.form)">
onMouseOver User moves the cursor over a link using the mouse links, images <a href="home.htm" 
onMouseOver="window.status('Click this link to go to my home page.')">
My Home Page</a>
onMouseOut User moves cursor off of a link using the mouse links, images <a href="home.htm" 
onMouseOut="alert('Why didn\'t you click?')">
My Home Page</a>
onLoad User loads the page in the browser document body, images <body onLoad="startAnimation()">
onUnload User exits the page in the browser document body <body onUnload="stopAnimation()">

Images and Animations

Object Method or Attribute Description Examples
image Image() constructor to create an image object var img = new Image()
image src set the URL of the image object img.src = "pic2.jpg"
form element name, src image tag in form of HTML document <img name="animation" src="pic1.jpg">
form element src sets or gets the URL of the image element document.forms[0].animation.src = img.src
window timerID = setTimeout(method, delay) waits delay milliseconds then calls method function animate() {
   setImage();
   timerID = setTimeout('animate()', 1000);
   timerRunning = true;
}
window clearTimeout(timerID) stops the animation function stopAnimation() {
   if (timerRunning) clearTimeout(timerID);
   timerRunning = false;
}

To Do After Class