Javascript Syntax
Basic Syntax for Javascript
Contents
Full documentation of Javascript can be found at Mozilla Developer Center
Using javascript in HTML
Top BottomTo 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 BottomSeveral functions exist to prompt for a user response:
- alert('myMessage') - pops up a message with an 'OK' button
- confirm('myMessage') - pops up a message with 'OK' and 'Cancel' buttons
- prompt(myMessage, myDefault) - prompts for user input, with optional default value
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 BottomThere are six basic variable types:
- Numbers
- Strings
- Booleans
- Arrays
- Functions
- 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 BottomMathematical
Top Bottom| Operator | Function |
| + | 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 BottomUnlike simple data types, objects come with methods and properties
String Objects
Top BottomDeclaring a string object:
var stringObject = new String('Not a simply a string. Has methods and properties.')
String Object methods:
| Method | Function |
| 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.length | Returns 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 BottomDeclaring a date object:
var todayObject = new Date('');
var otherDateObject = new Date(myYear, myMonth, myMonthDate, myHour, myMinutes, mySeconds);
var anotherDateObject = new Date("14 May 1964");
| Method | Function |
| myDate.getMinutes | the minutes component of date |
| myDate.getFullYear | four digit year component of date |
| myDate.getMonth | integer value for month: January = 0 |
| myDate.getDate | day of month |
| myDate.setDate(32) | sets date component to 32 of the month, that is 1 February if myDate.getMonth == January |
| myDate.setMonth | sets month value for date |
| myDate.toString() | Returns the date in sting format |
Math Objects
Top Bottom| Method | Function |
| 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 BottomDeclaring an array object:
var myArray = new Array('Yes', 'No', 'OK', 'Maybe');
| Method | Function |
| myArray.length | Returns 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 BottomIf
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 Bottomvar variable = condition ? trueValue:falseValue;
String Conversion
Top BottomString 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:
- parseFloat(userVar)
- parseInt(userVar)
- Number(userVar)
