The Sysadmin Notebook  

Sitemap

Javascript Syntax

Basic Syntax for Javascript

Contents

Full documentation of Javascript can be found at Mozilla Developer Center

Using javascript in HTML

Top Bottom

To include javascript in an HTML document, enclose the script within a <script> tag with type attribute of 'text/javascript'. In the interests of keeping content and behaviour seperate, and to meet the stricter specifications of XHTML, place your javascript in an external file and link to it in the header of your XHTML

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

Hello World

Top Bottom

Several functions exist to prompt for a user response:

The write() function of the document object allows us to insert HTML into the page, and is useful for debugging (displaying values of variables for instance), as are alert and confirm. Document.write adds a string to the document and the script must therefore be placed within the HTML file.

<script type="text/Javascript">
//One line comments begin with two forward slashes

/*
Multiline comments begin 
as above and end as below
*/

//alert produces a pop-up box
alert("Hello World");
//document write inserts text into document
document.write('<p>Hello World</p>');
</script>

Variables

Top Bottom

There are six basic variable types:

  1. Numbers
  2. Strings
  3. Booleans
  4. Arrays
  5. Functions
  6. Objects

Variables should be declared with the 'var' keyword unless you want a global variable

var myString = 'This will be saved for later';
var myCopyString = myString;
myString = prompt('Please enter some text');
var myArray = new Array("Dave Dee", "Dozy", "Beaky", "Mick" and "Twit");
myArray[4] = "Tich";
var myHashArray = new Array();
myHashArray('good') = 'Linux';
myHashArray('bad') = 'SCO Unix';
myHashArray('ugly') = 'Windows';

Operators

Top Bottom

Mathematical

Top Bottom
OperatorFunction
+addition or concatenation
-subtraction
*multiplication
/division
%modulus division
++increment
--decrement

Comparison

Top Bottom
Operator Function
== equal
!= not equal
> greater than
>= greater than or equal to
< less than
<= less than or equal to

Logical

Top Bottom
Operator Function
&& And
|| Or
! Not

Objects

Top Bottom

Unlike simple data types, objects come with methods and properties

String Objects

Top Bottom

Declaring a string object:

var stringObject = new String('Not a simply a string. Has methods and properties.')

String Object methods:

MethodFunction
myString.indexOf('text')Returns index where first letter of 'text' occurs in myString
myString.lastIndexOf('text')Returns index where last letter of 'text' occurs in myString
myString.substring(3,5)Returns substring that begins at index 3 and ends at index 5
myString.lengthReturns length of myString
myString.charAt(5)Returns character at index 5
concat(myString, anotherString)Joins multiple strings into one
myString.match(regexp)returns array of matches to perl-style regular expression

Date Objects

Top Bottom

Declaring a date object:

var todayObject = new Date('');
var otherDateObject = new Date(myYear, myMonth, myMonthDate, myHour, myMinutes, mySeconds);
var anotherDateObject = new Date("14 May 1964"); 
MethodFunction
myDate.getMinutesthe minutes component of date
myDate.getFullYearfour digit year component of date
myDate.getMonthinteger value for month: January = 0
myDate.getDateday of month
myDate.setDate(32)sets date component to 32 of the month, that is 1 February if myDate.getMonth == January
myDate.setMonthsets month value for date
myDate.toString()Returns the date in sting format

Math Objects

Top Bottom
MethodFunction
Math.round(myNumber)Rounds a number
Math.ceil(myNumber)Rounds number up
Math.floor(myNumber)Rounds number down
Math.round()Returns a random number between 0 and 1

Array Objects

Top Bottom

Declaring an array object:

var myArray = new Array('Yes', 'No', 'OK', 'Maybe');
MethodFunction
myArray.lengthReturns last index value of array plus 1
myArray.slice(1,4)Returns array of elements from index 1 to 4
myArray.concat(newArray, anotherArray)Returns array combining original three arrays
myArray.join(', ')Returns string joining elements with ', '
myArray.sort()Returns a sorted array
myArray.reverse()Returns a reverse sorted array

Conditional Statements

Top Bottom

If

Top Bottom
if (condition) {
	//do something
}
else {
	//do something else
}

Switch

Top Bottom
switch(condition) {
	case conditionOne:
	//code to execute 
	break; 
	case conditionTwo:
	//code to execute
	break; 
	case conditionThree:
	//code to execute
	break;
	default:
	//code to execute if no conditions match
}

'break' can also be used to prematurely terminate nested ifs

For

Top Bottom
for (initial-condition; loop-test; increment) {
	//code to execute
}
for (index in array) {
	//code to execute
}

While

Top Bottom
while (condition) {//code to execute}

'continue' can be used to terminate the remainder of a block and continue the loop at the next iteration

The do..while guarantees the code will execute at least once

do {//code to execute} while (condition)

The ternary operator

Top Bottom
var variable = condition ? trueValue:falseValue;

String Conversion

Top Bottom

String object methods can be used on simple string variables: an implicit conversion is performed, but the variable remains a string variable not a string object. Use typeof(myVar) to determine the type of a variable. Several methods exist to make an explicit conversion of a string variable: