Including JavaScript in XHTML Code

There are two ways to include JavaScript code - in a separate file or embed the code in xhtml file.

<script type = "text/javascript" src = "./jscript.js">

OR

<script type = "text/javascript">
    ...
</script>
   

Hello World Program

There are several ways to write Hello World using JavaScript. We could write code that embeds the output into the xhtml file or display a separate window with that text.

<script type = "text/javascript">
    document.writeln ("Hello World");
    alert ("Hello World!");
</script>

Identifiers in JavaScript

Identifiers in JavaScript must begin with a letter, _ (underscore), or $ (dollar) sign. Subsequent characters could be letters, underscores, dollar signs, or digits. Identifiers are case sensitive. However, by convention variable names start with letters and are in lower case.

Reserved Words
break delete function return typeof
case do if switch var
catch else in this void
continue finally instanceof throw while
default for new try with

Types

JavaScript is a weakly typed language. It has five primitive types - Number, String, Boolean, Undefined, and Null. The Undefined and Null are trivial types. The type Undefined has exactly one value undefined. The type Null has exactly one value null. There are two values for Boolean type - true and false.

A String is a finite ordered sequence of zero or more 16-bit unsigned integer values. There is no restrictions on what these values could be, but they usually represent 16-bit UTF-16 characters. A Number is a double precision 64-bit format IEEE 754 values. There are special values NaN (Not a Number), positive Infinity, and negative infinity.

JavaScript provides three 3 wrapper objects - Number, String, and Boolean. These objects have attributes and methods. The objects are created using the new expression and hold references (addresses)of where the objects are created in memory. The primitive types hold literal values.

JavaScript is a dynamically typed language. Variables are declared with the optional keyword let. It is recommended that variables be explicitly declared.

Operators

Arithmetic Operators: +, -, *, /, %

Increment and Decrement Operators: ++, --

Comparison or Relational Operators: ==, !=, <, <=, >, >=, ===, !===. The double == compares values and the triple === compares both values and types. Thus "3" == 3 is true but "3" === 3 is false.

Boolean Operators: && (AND), || (OR), and ! (NOT). Both the AND and OR operators are short circuit operators like they are in Java and C.

JavaScript has bitwise operations - & (AND), | (OR), and ~ (NOT). There are also the left shift (<<) and signed right shift (>>) and unsigned right shift (>>>). But these operators are hardly used in JavaScript.

Compound Assignment Operators: +=, -=, *=, /=, %=

Conditional Operator: The conditional operator acts like an if-else statement. Consider the following expression:

expr1 ? expr2 : expr3
If expr1 is true then expr2 gets substituted for the above else expr3 gets substituted.

Conditionals

The conditionals in JavaScript are similar to those in C and Java. We have: if and if-else. There is also the switch statement that follow similar rules.

switch (expression)
{
  case value1: // statement(s)
  case value2: // statement(s)
  ...
  default: // statement(s)
}

The expression can be numbers, strings, or booleans. The value of the expression should match one of the values in the case statements otherwise the default statements get executed. The break statement gets you out of the switch block.

Loops

The standard loops are available in JavaScript - while, do-while, and for.

while (expression)
{
  // statement(s)
}

do 
{
  // statement(s)
} while (expression);

for (init expr; control expr; incr expr)
{
  // statement(s)
}

The break statement takes you out of the loop. The continue statement skips the remaining statements in that iteration and starts the next iteration.

Arrays

In Java and C once an array is created its length remains fixed. Moreover arrays in those languages have elements only of one type. In JavaScript, however, the length of an array is dynamic and the elements of an array could be of mixed types. That is an array can contain numbers, strings, booleans, or references to other arrays or objects.

An array can be created in two ways - by using the constructor for an array or by explicitly enumerating the elements in the array. Here are examples of both:

let arr1 = new Array (100);

let arr2 = [1, "two", 3, "four"];

let arr3 = new Array ("one", 2, "three", 4);

The lowest index of an array is 0. There is an attribute called length. For example arr2.length will return 4. In JavaScript you can arbitrarily increase or decrease the length by assigning a value to the length attribute: arr2.length = 20. Since arrays are dynamic only assigned elements occupy space.

An array is an object in JavaScript and it comes with several useful methods - join, reverse, sort, concat, slice, push, pop, unshift, and shift.

join method concatenates all the elements of an array into a single string. If no delimiter is specified, the elements are separated by commas.

let colors = new Array ("red", "blue", "yellow", "green");
let colorString = colors.join(" : ");
// colorString = "red : blue : yellow : green";

reverse method reverses the order of the elements in the array.

let revColors = colors.reverse();
// revColors = ("green", "yellow", "blue", "red");

sort method coerces the elements of the array to be strings and then sorts them into alphabetical order.

colors.sort();
// colors = ("blue", "green", "red", "yellow");

concat method is called with zero or more arguments item1, item2, ..., it returns an array containing the array elements of the original array followed by the array elements of each of the arguments in order.

let newColors = colors.concat ("orange", "purple");
// newColors = ("red", "blue", "yellow", "green", "orange", "purple");

slice method takes two arguments, start and end and returns an array from element start upto but not including the element end. If the end element is not specified then all the elements from start to the end of the array is returned.

let colors2 = newColors.slice (1, 3);
// colors2 = ("blue", "yellow");

push method when called with arguments item1, item2, .. appends these arguments to the end of the array in the order in which they appear.

colors.push ("pink");
// colors = ("red", "blue", "yellow", "green", "pink");

pop method removes the last element of the array.

let someColor = colors.pop();
// someColor = "green";
// colors = ("red", "blue", "yellow");

shift method removes the first element of the array.

let myColor = colors.shift();
// myColor = "red";
// colors = ("blue", "yellow", "green");

unshift method when called with arguments item1, item2, .. prepends these arguments to the start of the array such that their order in the array is the same as the order in which they appear in the argument list.

colors.unshift ("violet");
// colors = ("violet", "red", "blue", "yellow", "green");

Functions

The function definition consists of a header and a body. The header has the keyword function followed by a list of optional formal parameters. In the body of the function there could be 0 or more return statements.

// This function takes two numbers and returns their sum:

function addTwo (a, b)
{
  return (a + b);
}
...
let x = 2.3;
let y = 4.5;
let z = addTwo (x, y);

The definition of a function must precede the call to a function. For this reason function definitions are normally put in the head of the xhtml document.

The function is called with a list of actual parameters. JavaScript does not check that the type and number of the actual parameters matches with the formal parameters. A function could accept a variable number of parameters. Each function has an attribute called arguments that can only be refered to inside the function. arguments is an array that holds the parameters passed to the function. We can always find out the actual number of parameters passed to the function by checking the length of the array arguments.

// This function adds any number of variables

function addAll ()
{
  let sum = 0;
  for (let i = 0; i < arguments.length; i++)
    sum = sum + arguments[i];
  return sum;
}
...
let p = addAll (x, y, z);

Primitive types are passed by value and objects are passed by reference. Variables inside a function have local scope if they are explicitly declared using the let keyword, otherwise they have global scope. A variable declared explicitly inside a function hides a global variable of the same name declared outside the function.

In JavaScript, functions are looked upon as objects. So one can create references to them and pass them to other functions as an actual parameter.

let refFun = addAll;
...
let k = refFun (m, n, o);

// Simple math functions
function add (x, y) { return x + y; }
function sub (x, y) { return x - y; }
function mult (x, y) { return x * y; }
function div (x, y) { return x / y; }

// Here is a function that takes the above functions as parameters
function operate (operator, operand1, operand2)
{
  return operator (operand1, operand2);
}

// To compute the value of (2 + 3 ) + (4 * 5) we can do
let val = operate (add, operate(add, 2, 3), operate (mult, 4, 5));

JavaScript supports recursion - a function could reference itself.