The JavaScript Programming Language

Javascript is a scripting language used in conjunction with HTML documents. It is an object oriented language similar to several others. For security reasons disk I/O is severely restricted. Generaly, one may not read or write files on the client machine. Also, JavaScript does not have the ability to access files on the server. A CGI program is generally required for such activity.

Perhaps the simplest use of Javascript is to write static or dynamic content directly to the web page, in line with HTML code. JavaScript functions and instructions are embedded in HTML documents. JavaScript relies on HTML objects to execute.

Objects
Many types of objects are accessible to JavaScript programs. Objects include the current document, a window, a command button or a URL to name a few.
Objects have
Properties
These are the attributes of an object.
Methods
These are functions/procedures which may be performed on an object.
Events
These are actions which happen to an object
A sample Javascript program - use "View Source" after you connect to this page to see the program.
Also, a JavaScript is located at the bottom of this page. It writes a standard ending to an HTML file.

Comments
Javascript supports single and multiline comments.
//This is a single line comment. Note the double forward slashes
/*This is a multi-line comment
Note that the comment begins with the /* sequence and ends with */

DataTypes and Variables
As with most programming languages Javascript contains
numbers - these operate as one would expect. JavaScript does not enforce typing of variables so, in general, integers, float, double, etc. are processed the same. JavaScript does recognize the difference between an integer and a float, for example, and treats them different in special contexts

strings - these follow the conventions for defining strings in most other languages.

variables - must begin with a letter or an underscore and may contain digits. It is extrememly important to remember that names are case-sensitive in JavaScript. So, for example, count, Count and COUNT are all different variables.

Javascript declarations The basic Javascript declaration is of the form
var variableName = value;
Note: = value is optional.

Scope
Local Variables - Declared within a function
Global Variables - Declared outside of all functions

Literals
Javascript supports the following types of literals
Operators
Javascript uses the usual operator precedence and supports a typical complement of operators including:
Arithmetic Operators
+, -, * and /
Add, subtract, multiply and divide
++, --
Autoincrement and autodecrement
%
Modulus ( x % y is the remainder of x divided by y)
Assignment Operators
=
Ordinary assignment
+=
Assign and accumulate (x += y is the same as x = x + y)
-=
As above using - rather than + (i.e. x = x - y)
*=
As above
/=
As above
%=
Modulus accumulate (i.e. x %= y is the same as x = x % y)
And several others not listed
Comparison Operators
==
equals - IMPORTANT: the equals comparison operator is two consecutive equal signs. If you mistakenly use only one equal sign your program will behave in a seemingly erroneous fashion.
!=
not equals
>
greater than
>=
greater than or equal to
<
less than
<=
less than or equal to
Logical Operators
&&
And
||
Or
!
Not

Conditional Statements
IF-(THEN)-[ELSE]
if (condition)
{
  sequence of statements
}
else
{
  sequence of statements
}
NOTE: There is no THEN and the ELSE is optional.

Loop Statements
for Loop
for ([initial-expression;][condition-expression;][increment-expression]) {
  sequence of statements
}
Example:
//Compute the sum of the first 10 positive integers
Sum = 0
for (i = 0; i <= 10; i++){
  Sum = Sum + i
}

while Loop
while (condition) {
  sequence of statements
}
Example:
//Compute the sum of the first 10 positive integers
Sum = 0; i = 1;
while (i <= 10) {
Sum = Sum + i++
}

break and continue Statements
The break statement is used to exit a loop. Execution resumes at the first statement following the end of the loop.
The continue statement immediately forces the next iteration of the loop. I.e. it causes execution to resume at the top of the loop.

Object Manipulation Statements
JavaScript contains several statements used exclusively for manipulating objects.
For - In
for (<variable> in <object>)) {
  sequence of statements
}
Example:
i = 0
for (prop in document) { //Note: try "this" instead of "document"
  i = i + 1
  document.write(i + ": " + prop + " = " + document[prop] + "<br>")
}

this enables one to refer to the current object without knowing its name. Use this as if it were a variable pointing to the current object.

new enables one to create a new instance of an object.

with enables one to reference an object in a sequence of statements without having to specifying the object in each statement.
Example:
z = Math.tan(a)
w = Math.sec(a)
. . .
is equivalent to
with Math
z = tan(a)
w = sec(a) ...

Functions
Functions are defined in JavaScript much the same as in many other programming languages.
Functions should be defined in the HEAD section of an HTML document and within the <SCRIPT> tag.
The syntax of a function definition is as follows:

function FunctionName(ParameterList) {
  sequence of statements
}

Example of using functions:

Here is a more complete explanation of passing parameters in Javascript.

Some Native JavaScript Functions

alert(message) - displays the javaScript alert box containing the specified message. Besides the obvious uses, this is also useful as a debugging tool. It is a convenient means of displaying information about program state such as the content of a variable.


confirm(message) - similar to alert. Displays a dialog box containing message and "OK" and "Cancel" buttons. confirm returns true or false depending on the button that is clicked.


Prompt allows the user to send information to the program. It displays a message from the program, a textbox for user response, an OK button and a Cancel button.

history.back() - loads the previous URL in the history list.

history.forward() - loads the next URL in the history list.

Controlname.blur() - removes focus from the specified control.

Controlname.focus() - gives focus to the specified control.

Stringname.charAt(position) - returns the character in the specified position of Stringname.

SearchedStringname.indexOf(SearchString [,StartPosn]) - finds the first occurrence of SearchString in SearchedString (optionally) beginning at position StartPosn.
Note the capitalization of charAt and indexOf!

close - is a method to close a document or a window object.

eval(JavaScript_expression) - an extremely powerful function. eval accepts a JavaScript expression as a parameter, evaluates the expression and returns the result.

Math functions - the usual complement of math functions including trig functions and log are part of the Math library (object) along with certain constants such as Pi.

isNaN(parameter) - returns true if parameter is a number and false otherwise.

Arrays in JavaScript
Arrays in Javascript may conrtain strings or numbers. They may be dimensioned or left undimensioned. Array elements are initialized to null.

Example declarations

UndimArray = new Array()

MixedArray = new Array("a string in position 0", 4.9)

DimmedArray = new Array(100)

Note that in the declaration immediately above, DimmedArray is declared to have 100 elements numbered from 0 to 99.
One may determine the number of elements of an array programmatically by referencing the .length property of the array. For example, DimmedArray.length is equal to 100.

Arrays support the following methods:
Some Special JavaScript Objects

string - a string variable. An example declaration follows.
var stringname = new string("string contents")

document - the curent document. This object has many properties. Use the property inspection Javascript to view the properties

window - the current window or one created during execution of the javaScript.

image - an image referenced in an HTML document

Math - this is basically a library of math functions and constants.

history - the URL history list.

Date - a date object has many methods for setting or retrieving parts of dates (day, month, year).

Common Form Control Objects
radio
a radio button
option
an option button
checkbox
a check box
select
used to present a list box from which the user may choose one or more items.
button
a command button
text
a text box
textarea
holds multi-line text
password
a box in which to type a password. The password is masked with *s.
hidden
holds data which the user cannot see
reset
a reset button
submit
a submit button


Top of this page   Top of page      Home page   Home page