Beginner's JavaScript

Java without all the tedious programming? Not quite.

1 2 3 Page 2
Page 2 of 3

The basic set of mathematical operators are + (addition), - (subtraction or arithmetic negation), * (multiplication), / (division), % (modulo, or remainder after you divide) and = (assignment); as a side note, the lvalue for the assignment operator is always a variable. In addition to these operators, there are -- (decrement an integer variable) and ++ (increment a integer variable), bitwise operators such as || (OR two values), && (AND two values), ! (NEGATE a value), ^ (XOR two values), << (shift bits to the left), <<< (shift bits to the left and fill spaces with zeros), >> (shift bits to the right) and >>> (shift bits to the right and fill spaces with zeros.) With the exception of the increment, decrement, and arithmetic negation, each of these operators can be combined with the assignment operator like += (increment lvalue by the amount in the rvalue). The combination assignment operators are there as a shorthand when performing a mathematical operation on a variable and then assigning the result of that operation back to the variable:

variable = variable * 42;
// The above line is identical to the next line variable *= 42;

To allow more complex calculations, you can use the parentheses to section the parts of the calculation.

zzz = (xxx * 32) / (yyy + xxx);

For logical or numerical comparison, operators are as follows: < (less than), > (greater than), == (equal to), != (not equal to), <= (less than or equal to), >= (greater than or equal to). Please keep in mind the significant difference between == and =. It is one of the most common mistakes made by novices in the C language, and in JavaScript as well. BASIC programmers should also know that != and not <> is used as the not-equal-to function. The semicolons that you see at the end of each line are used to separate different "lines" of code. You can actually have a number of executable code segments on the same line of text. This has the same effect as keeping the two lines separate. It just saves space if needed. For example,

variable *= 42; zzz = (xxx * 32) / (yyy + xxx);

Aside from being used as a mathematical addition operator, the plus sign (+) is used as a concatenation operator if its lvalue or rvalue is a string. For example,

yourname = "Dave" 
line_of_text = "What are you doing " + yourname + "?"; 

The variable, line_of_text, now becomes "What are you doing Dave?"

The quotation marks are used to indicate strings. The single-quote character (') can also be used to delineate a string. You need a pair to indicate the start and end of the string. The difference between the two is that the standard double-quote mark (") allows special character combinations to indicate non-printable ASCII characters like the tab, newline, etc. To indicate these meta-characters you use the backslash (\) character. For example, the tab is indicated with a \t. The backslash is also used for escape operators that would otherwise be misunderstood. To print the backslash character itself, you simply use two of them (\\) in your string.

The brackets are used in a special data type known as the array. An array is a set of values of the same type that can be indexed directly. For example, to access the first element of an array, you would use myarrary[0]. Note that arrays start at 0, not 1. We will take a more in-depth look at arrays later. The braces ({ and }) are used to indicate a block of statements. These blocks are used inside language constructs like the common if...then...else construct and the while loop, and as delimiters for functions.

Comments are delimited with /* and */, or you can use // to indicate that any following characters to the end of a line comprise a comment. The last operator uses two characters -- the question mark (?) and the colon (:). The ? : operator is shorthand for the if...then...else language construct. The same statement could otherwise be written using the reserved words if and else. For example,

if (notMine == true)
{
   someoneElses = true;
}
else
{
   someoneElses = false;
}

can be easily rewritten in shorthand as:

someoneElses = (notMine == true) ? true : false;

Finally, as a note to C and C++ programmers, the * and -> operators do not exist. Perl programmers should know that the dollar sign ($) is not used to indicate variables and the pound sign (#) is not used to indicate the start of a comment in your code. Perl programmers will find (to their dismay) that there are no pattern-matching or substitution operators either.

Data types and variables

The four basic data types available in JavaScript are the object (a generic data type that can be anything), the number (floating point or decimal), the string (a set of text characters), and the boolean (true or false values). A variable is indicated by a word name and is case sensitive. Variable names also allow for the use of the underscore character (_), but nothing else other than ASCII alphanumeric characters. Also, variable names can begin only with an alphabetic character, not a number or underscore. The example below shows several variables being assigned values.

myvariable = "A line of text";
count = 0;
Super_Long_VariableNamethatishardtoread = "";
WorldIsRound = true;

The first variable is a string. The second variable stores a numerical value, and the third is another string (currently blank). The last is a boolean value that can be either true or false. With these basic types it is possible to do much of the work. In addition, there are two more advanced data types known as the array and the function pointer.

Statements

Statements are whole executable lines of JavaScript; they give structure to a script. Without these constructs, it is possible to do only simple operations and built-in functions. Each construct employs one or more reserved words. Here is a full table of these reserved words for currently implemented statements:

break           comment         continue 
for             for...in        function 
if...else       return          var 
while           with    

In truth, there is another entire series of reserved words that have not been implemented in the current release of JavaScript but are still recognized by the interpreter and cannot be used within your code:

abstract        boolean         byte            case 
catch           char            class           const 
default         do              double          extends 
false           final           finally         float 
goto            implements      import          instanceof 
int             interface       long            native 
null            package         private         protected
public          short           static          super 
switch          synchronized    throw           throws 
transient       try             void    

These words primarily are reserved words in Java that currently are not implemented in JavaScript.

If...else

The simplest to grasp is the if..then...else construct. Basically, if a condition is true, the script will perform a certain action; if it is not true then it will do something else. For example,

if (variable > 20)
{
   ...
   ...
}
else
{
...
}

The actions are kept within blocks of statements. You can combine these into a whole series of if...else constructs tagged on after the else. Unfortunately, there is no switch statement right now to provide a comparison of one value to a set of others and perform statements for each.

While

The while loop provides a means of repeating a series of commands while a certain condition is true. It is certainly possible to be stuck forever within a while loop if the condition never becomes false, so make sure you have a way out.

count = 0;
while (count < 10)
{
   write("Hello.\n");
   count++;
}

For

A more subtle way of performing the same action, as shown in the example for the while loop, is to use the for loop. It is another shorthand that makes things easier to read, but for all intents and purposes it is identical in function to the previous example.

for (count = 0; count < 10; count++)
{
  write("Hello.\n");
}

There are three sections within the parentheses; the initialization phase count = 0; the comparison phase count < 10; and the modification phase count++. The initialization phase is executed only once before the body of the loop begins. Next, the comparison phase checks the status of the loop. Then the body of the loop itself is executed. Once the body is done, the modification section is executed. As you can see, each of these phases or sections is separated by a semicolon.

For..in

The for..in construct executes a block of code for all elements in a set of data. For example,

for count in myArray
{
  write(myArray[count]);
}

This example script will print the contents of each and every element in the array.

Function

The function keyword begins the definition of a subroutine that can be called in other parts of the program. A function is declared as:

function myfunction(parameter1, parameter2)
{
  // body of the function
}

The keyword is followed by a name for the function. The rules for function names are the same as for variable names. After the name within the parentheses is a list of all the parameters. In our example the function has only two parameters, but it actually can have as many parameters as you need. Unlike C and other languages, the loose typing of JavaScript does not require that you indicate what data type these parameters are. The data types are interpreted when the function is called elsewhere. For example, suppose we have defined a function to find the average of two numbers. This function can be called in the code else as shown below.

xxx = 23;
yyy = 14;
averaged_value = Average(xxx, yyy);

After any processing within itself, the function can return a value by using the return keyword followed by a value. The actual code for the Average function we used above might be:

function Average(value1, value2)
{
  average = (value1 + value2) / 2;
  return average;
 }

Break, continue

The break and continue keywords are used in loops to effect a forced escape out of the loop, or to skip past the rest of the code within a block and continue the loop in its next iteration. For example,

count = 0;
while (count < 10)
{
  if (count == 5) 
    break;
  write(count + "...");
  count++;
}

This example script prints out the numbers 0 through 5, although the loop conditional says it should continue iterating until count becomes 10. The if..then with the break statement causes the loop to end at 5.

Let's look at another example.

for iteration in myArray
{
   if (Math.odd(iteration))
     continue;
   writeln(myArray[iteration]);
}

This example makes use of the Math function to check for odd numbers in the iteration and prints out only the values contained in the even slots of the array.

Using objects

A small set of objects are readily available for use within your code. In C and BASIC, these are usually known as library functions and can be used to perform trigonometric functions, print information to the screen, etc. The object is the basic unit of object-oriented programming systems (OOPS). Each object usually has certain features or variables and also a set of functions or methods associated with the object. Please note that we use the words function and method interchangeably; true OOPS programmers only refer to them as methods, but to bring some familiarity to readers who have done programming in non-object-oriented languages like C and BASIC, we will continue using this term interchangeably.

anchor          the HTML anchor tag object
applet          a Java applet object; currently this is not yet 
implemented
button          an HTML INPUT tag of type "button" 
checkbox        an HTML INPUT tag of type "checkbox"
Date            an object that contains a variety of methods to print, 
                calculate, and interchange dates
document        the object describing an HTML page 
form            the controlling object for an entire HTML FORM 
history         an object of the current browsers history list
link            an HTML link object
location        an object describing a URL
Math            an object that contains mathematical constants, 
trigonometric
                functions, and other basic non-arithmetic methods
password        an HTML INPUT tag of type "password"
radioButton     an HTML INPUT tag of type "radio"
reset           an HTML INPUT tag of type "reset"
selection       a text selection within the HTML TEXTAREA or INPUT type 
"text" tags
string          the string data type with a variety of methods for 
printing and
        manipulating strings
submit          the HTML INPUT tag of type "submit"
text            the HTML INPUT tag of type "text"
textArea        the HTML TEXTAREA tag (Note: the selection object is 
separate
        from the textArea object itself)
window          the object describing the current browser or document 
window

Descriptions of JavaScript objects

This list of JavaScript objects is exhaustive to what has been implemented in Netscape Navigator. You have already seen us use the write and writeln, two of the most commonly used methods that are automatically interpreted as part of the document object. You have also seen the use of the Math object. Of this list, most are basic tags you would find in an HTML FORM. Other useful but less-easily understood objects are the window and the document objects that control behavior of the document itself. You will notice that no objects for opening files or network connections exist yet. Currently this is a security risk, but there is hope for the future: Vendors are making noise about including such features to create a more powerful scripting language.

Event handlers

Most of the functions of JavaScript are invoked within a FORM or document with the help of event handlers. Each FORM type has a set of events that it responds to such a selecting a checkbox or defocusing or "blurring the focus" of a text field. The complete list of event handlers and what event they respond to is shown below:

1 2 3 Page 2
Page 2 of 3