Module 1 An Introduction To JavaScript
by K. Yue, revised September 29, 2000
Copyright 2000

1.1 Introduction

<script language= "JavaScript">
<!--
    // JavaScript code follows.
    ...
    // ... -->
</script>

Example 1 HelloWorld.html

<html>
<head>
<title> Hello World </title>
</head>
<h1> Hello World </h1>
<body>
A Simple Hello World Page.
<br>
<script language = "JavaScript">
<!-- This is HTML comment to hide code from older browsers.
    // JavaScript comment is similar to Java.
    document.write("JavaScript generated Hello World!")
    // document is a built-in object.
    // end JavaScript code -->
</script>
<p>
Regular HTML stuff.
</body>
</html>

<noscript>
Sorry, you browser does not support JavaScript.
Please get one.
</noscript>

Example 2 BeerAlert.html

<html>
<head>
<title>JavaScript-generated Alert Window</title>
</head>
<body>
JavaScript-generated Alert Window
<p>
<form>
<input type= "button"
    name= "helloWorld"
    value= "Click here for a beer"
    onClick = "alert('JavaScript:\nSorry, you are underaged.')">
</form>
</body>
</html>

Example 3 LastModified.html

Try to convert the following to modern Javascript code and solve the Y2K problem.

<html>
<font size ="2: color="blue">
<script language="JavaScript">
<!-- // old method.
function makeArray(n) {
    this.length = n;
    for (var i=1; i<=n; i++)
    this[i] = 0;
    return this;
}

month = new makeArray(12);
// new method: month = new Array([12]);

month[1] = "January";
month[2] = "February";
month[3] = "March";
month[4] = "April";
month[5] = "May";
month[6] = "June";
month[7] = "July";
month[8] = "August";
month[9] = "September";
month[10] = "October";
month[11] = "November";
month[12] = "December";

today = new Date(document.lastModified);
document.write("Last Modified: " + month[today.getMonth()+1]);
document.writeln(" " + today.getDate() + ", 19" + today.getYear());
//   -->
</script>
</font>

1.2 Lexical Structures, Variables and Data Types

Example:

i = 1;
i = "This is fun.";

var i;

Example:

s = "my hobbies:";
message = "This is good" + myFriend;
warning = "Warning # " + warningId " issued.\n";
i = s.length; // i = 11.
i = s.charAt(3); // i = 'h'.
i = s.charAt(s.length-1); // i = ':'.
i = s.indexOf('b');

1.3 Functions

Example:

function length(x1, x2, y1, y2) {
    return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}

Example: myfun.html

function length(x1, y1, x2, y2) {
     return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}

document.write(length(1,1,3,3) + "<br>");
myfun = length;
document.write(myfun(1,1,5,5) + "<br>");

Example: from Flanagan

<script>
//   We define some simple functions here
function add(x,y) { return x + y; }
function subtract(x,y) { return x - y; }
function multiply(x,y) { return x * y; }
function divide(x,y) { return x / y; }

// Here's a function that takes one of the above functions
// as an argument and invokes it on two operands
function operate(operator, operand1, operand2) {
    return operator(operand1, operand2);
}

// We could invoke this function like this to compute
// the value (2+3) + (4*5):
var i = operate(add, operate(add, 2, 3), operate(multiply, 4, 5));

// Now we store the functions defined above in an associative array
var operators = new Object();
operators["add"] = add;
operators["subtract"] = subtract;
operators["multiply"] = multiply;
operators["divide"] = divide;
operators["pow"] = Math.pow; // works for predefined functions too.

// This function takes the name of an operator, looks up
// that operator in the array, and then invokes it on the
// supplied operands. Note the syntax used to invoke the
// operator function.
function operate2(op_name, operand1, operand2) {
    if (operators[op_name] == null)
        return "unknown operator";
    else
         return operators[op_name](operand1, operand2);
}

// We could invoke this function as follows to compute
// the value ("hello" + " " + "world"):
var j = operate2("add", "hello", operate2("add", " ", "world"))

// Using the predefined Math.pow() function
var k = operate2("pow", 10, 2);
</script>

Example: from flanagan

<script>
function max() {
    var m = -Number.MAX_VALUE;
    // loop through all the arguments, looking for, and
    // remembering, the biggest.
    for(var i = 0; i < max.arguments.length; i++)
        if (max.arguments[i] > m) m = max.arguments[i];
        // return the biggest.
            return m;
}

var largest = max(1, 10, 100, 2, 3, 1000, 4, 5, 10000, 6);
</script>

Example:

function nextCycle() {
    nextCycle.count++;
    if (nextCycle.count >= nextCycle.MAX) {
         nextCycle.count = 0;
    }
    return nextCycle.count;
}

nextCycle.MAX = 10;
nextCycle.count = nextCycle.MAX;

Exercise 1:

Write a function nextColor() that returns a color string by looping through the following colors cyclically: "red", "blue", "green", "yellow", "white", "brown" and "black".