Programming in JavaScript

JavaScript syntax is pretty similar to Java syntax except functions and variables are untyped.

Variable Declarations and Expressions

var x = 100, y = "100", z;
z = x + x; // z = 200
z = y + y; // z = "100100"

Conditionals

if (EXPRESSION) STATEMENT;
if (EXPRESSION) STATEMENT; else STATEMENT;
switch(KEY) {
   case VALUE: STATEMENT; ... break;
   case VALUE: STATEMENT; ... break;
   ...
   default: STATEMENT;
}

Blocks

{ STATEMENT; ... }

Iterations

while(EXPRESSION) STATEMENT;
for(var LCV = INIT; LCV < STOP; LCV++) STATEMENT;
do { STATEMENT; ... } while (EXPRESSION);

Functions

Functions are just special types of objects:

var square = new Function("x", "return(x * x)");

Here's a more friendly syntax:

function square(x) { return x * x; }

Example: Pascal's Triangle

Recall that Pascal's triangle is a triangular array of numbers. The entry in row n, column m is:

choose(n, m) = # of ways to choose m items from n items

We can compute choose(n, m) as follows:

choose(n, m) = n!/(m! * (n m)!)

A JavaScript implementation can be found in pascal.html.

Object-Based Programming

Object-oriented languages can be divided into class-based languages like C++ and Java and object-based languages like JavaScript. Object-based languages don't have the concept of classes.

Users can create objects or use built-in objects. An object can have constructors, properties, methods, and event handlers.

Creating Generic Objects

myCustomer = new Object();
myCustomer.firstName = "Bill";
myCustomer.lastName = "Ding";
myCustomer.id = 4289;

myCustomers = new Array(10);
myCustomers[0] = myCustomer;

Example/Utility

The file oop.html contains the objectToTable() function, which uses the for/in statement to iterate through the fields of a generic object and writes them to the rows of a table.

Defining Methods and Constructors

Using the implicit parameter, this, we can create methods and constructors. The file oop2.html shows how this is done.