Introduction to JavaScript
This document is Copyright (c) Information Technology Group, |
This document is an introduction to some of the most frequently used
components of the JavaScript programming language. The various
language characteristics and elements are gradually introduced,
attempting to create a document structure such that each new element
being presented to rely as little as possible on elements that are
introduced at a later time (this is not always possible, as some
language features are intr-related in a "circular" way).
The reader of this document is assumed familiar with the basic
structure of a simple HTML document, as well as with the C programming
language.
JavaScript is a scripting language, designed for being embedded in HTML documents, and exectuted directly in an HTML browser. The following diagram illustrates how a JavaScript program interacts with the display objects described in an HTML document, and thus (indirectly) with the user (reader) of the document.
HTML Browser <---------------------------------------\ |
<html> <!-- the start of the HTML document --> |
{ // the Code Block begins with '{' |
var varName; |
var varName = value; |
varName = value; |
var myObject = new Object; // 'myObject' is a pointer to a |
var myVariable = "string_value"; // the variable now holds a string value |
var myVariable = 'something'; |
// somewhere in a code block: |
var globalVariableName = value; |
var globalVariableName = 255; // a global variable |
function f() { |
function f() { |
var myVariable = 1; // a global variable |
// a function that assigns an un-declared variable, which is thus implicitly global |
Associativity | Operator | Operand type(s) | Operation performed |
L | ( ) | function, arguments | Function call |
R | ++ | lvalue | Pre- or post-increment (unary) |
R | -- | lvalue | Pre- or post-decrement (unary) |
R | - | number | Unary minus (negation) |
R | + | number | Unary plus (no-op) |
R | ~ | integer | Bitwise complement (unary) |
R | ! | boolean | Logical complement (unary) |
R | typeof | any | Return data type (unary) |
R | void | any | Return undefined value (unary) |
L | *, /, % | numbers | Multiplication, division, modulo |
L | +, - | numbers | Addition, subtraction |
L | + | strings | String concatenation |
L | << | integers | Left shift |
L | >> | integers | Right shift with sign-extension |
L | >>> | integers | Right shift with zero extension |
L | < , <= | numbers or strings | Less than, less than or equal |
L | >, >= | numbers or strings | Greater than, greater than or equal |
L | == | any | Test for equality |
L | != | any | Test for inequality |
L | === | any | Test for identity( checks whether its two operands are "identical" using a strict definition of sameness) |
L | !== | any | Test for non-identity |
L | & | integers | Bitwise AND |
L | ^ | integers | Bitwise XOR |
L | | | integers | Bitwise OR |
L | && | booleans | Logical AND |
L | || | booleans | Logical OR |
R | ?: | boolean, any, any | ( exp1 ? exp2 : exp3 ) If exp1 is 'true', the exp2 is evaluated, otherwise exp3 is evaluated. |
R | = | lvalue, any | Assignment |
R | *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^=, |= | lvalue | Assignment with operation |
L | , | any | Multiple evaluation |
function myFunc(paramVariable1, paramVariable2, ... paramVariableN) |
// example: |
// example (as above, but using objects): |
// check to see if 'parameter2 ' has been passed to the function: |
if (boolean_expression){ statements } |
if (boolean_expression){ statements } |
switch(expression) { |
while (boolean_expression) { statements } |
do { statements } while (boolean_expression) |
for (initialization_expression; boolean_expression; end_of_loop_expression) |
initialization_expression; |
for (i=0;;i++) { |
for (i=0; i<10; i++) { |
for (myString=""; !stringContains(myString, " stop"); appendToString(myString, readACharacter())) { |
for (...) { |
for (...) { |
try { |
try { |
function someFunction() { |
// a function that simply throws an exception |
var myObject = new Object; // the variable 'myObject' now holds a pointer (a reference) |
// declare and initialize statically named properties for 'myObject' |
// declare and initialize properties with dynamically created names |
var v = myObject.firstProperty; // read the 'firstProperty' of 'MyObject; 'v' becomes '1234' |
var mySecondObject = new Object; // declare a new object, |
function myFunction(argument) { |
// note the use of the 'function' keyword below: |
// add a property to an object, assign it a value, and then delete it using the 'delete' operator |
// somewhere in a code block: |
// this function will later be attached to the method 'secondMethod' of 'myObject' (see code below); |
// this is a constructor function to build an "empty" object |
// this constructor function builds an object with a property 'objProperty' |
// this constructor function builds an object with a property 'objProperty' and a method 'objMethod' |
// object constructor that initializes its 'data' property and "embeds" the code of its 'print' method: |
// this constructor function builds 'Person' objects that may or many not have |
var myObject = { |
var userDefinedField = "my field" |
// add a new property to the type String |
// declare and initialize a dynamically-named variable |
// change 'Object' prototype |
// change 'Object' prototype |
// array declaration without initialization: |
var arrayObject1 = new Array("a string"); // this declares and initializes a 1-element array |
// array (re)initialization: |
// when an array is initalized with specified values as its elements, the |
// create an Array object |
var row0 = new Array(row0_col0, row0_col1, row0_col2); |
Property | Description | Syntax |
length | Sets or returns the number of elements
in an
array. Note: Unlike arrays declared in C, JavaScript allows the size of an array to change dynamically at any time. It is possible to write directly to a position that was not even declared using the [ ] operator. The length of the array can also be changed by altering the length attribute of the Array object: if the length of the array is set to a smaller value that its actual length, then the elements "in excess" are deleted. |
myArray.length
= resizeLength; arrayLength = myArray.length; |
Method | Description | Syntax |
concat() | Concatenates one or more arrays to the end of the array that called the method and returns the result. The array that called the method is not changed by the method. | resultArray = myArrayObject.concat(array1,array2,..) |
join() | Puts all the elements of an array into a string. The elements are separated by a specified separator | stringObject = myArrayObject.join([separator]) |
reverse() | Reverses the order of the elements in an
array. |
myArrayObject = myArrayObject.reverse() |
slice() | Returns a new array that contains the elements of the original array starting at index position start and ending at the element position before end. If no end position is specified, the new array will contain the elements of the original array, starting at the position start through the end of the array. | resultArray = myArrayObject.slice(start [,end]) |
sort() | Rearranges the elements of the array based on a sorting order. If the method has no parameters,JS attempts to convert all the elements of the array to strings and then sort them alphabetically.If the array should be sorted some other way, a function must be provided to handle the new sorting algorithm. | myArrayObject =
myArrayObject.sort([sortby]) |
splice() | Removes or adds new elements to an array;
|
myArrayObject =
myArrayObject.splice(index,N,elem1,...elemX) |
// dateObject object will automatically hold the current date and time as its initial value! |
Get Methods |
Set Methods |
Parameters Value | Description | Syntax |
getTime( ) | setTime(val) | 0-... | Returns/Sets the equivalence of the Date object in milliseconds. The milliseconds are expressed as an integer representing the number of milliseconds between midnight January 1, 1970 (GMT) to the date and time specified in the Date object. | dateObject.getTime() |
getSeconds( ) | setSeconds(val) | 0-59 | Returns/Sets the seconds portion of the Date object expressed as an integer from 0 to 59. | dateObject.getSeconds() |
getMinutes( ) | setMinutes(val) | 0-59 | Returns/Sets the minutes portion of the Date object expressed as an integer from 0 to 59. | dateObject.getMinutes() |
getHours( ) | setHours(val) | 0-23 | Returns/Sets the hour portion of the date expressed as an integer from 0 (12:00 a.m. midnight) to 23 (11:00 p.m.) | dateObject.getHours() |
getDay( ) | setDay(val) | 0-6 | Returns/Sets the day of the week expressed as an integer from 0 (Sunday), 1 (Monday) to 6 (Saturday). | dateObject.getDay() |
getDate( ) | setDate(val) | 1-31 | Returns/Sets the day of the month expressed as an integer from 1 to 31 | dateObject.getDate() |
getMonth( ) | setMonth(val) | 0-11 | Returns/Sets the month portion of the Date object expressed as an integer from 0 (January) to 11 (December). | dateObject.getMonth() |
getFullYear( ) | setFullYear(val) | 1970- ... | Returns/Sets the year in local time as a full four-digit number. | dateObject.getFullYear() |
toGMTString() | - | - | Returns a string representation of the Date object in GMT format, e.g.: "Tue, 11 Sep 2001 13:30:00 XXX" (XXX is GMT on firefox, UTC on IE6) | dateObject.toGMTString() |
getTimezoneOffset() | - | 0- ... | Returns the getTimezoneOffset() method returns the difference between the time zones of local time and Greenwich Mean Time (GMT). This difference is returned as an integer representing the number of minutes between the time zone of the local time and GMT. | dateObject.getTimezoneOffset() |
Property | Description | Syntax |
E | Returns Euler's constant (approx. 2.718) | Math.E |
LN2 | Returns the natural logarithm of 2 (approx. 0.693) | Math.LN2 |
LN10 | Returns the natural logarithm of 10 (approx. 2.302) | Math.LN10 |
LOG2E | Returns the base-2 logarithm of E (approx. 1.442) | Math.LOG2E |
LOG10E | Returns the base-10 logarithm of E (approx. 0.434) | Math.LOG10E |
PI | Returns PI (approx. 3.14159) | Math.PI |
SQRT1_2 | Returns the square root of 1/2 (approx. 0.707) | Math.SQRT1_2 |
SQRT2 | Returns the square root of 2 (approx. 1.414) | Math.SQRT2 |
Method | Description | Syntax |
abs(x) | Returns the absolute value of a number | Math.abs(x) |
ceil(x) | Returns the value of a number rounded upwards to the nearest integer | Math.ceil(x) |
cos(x) | Returns the cosine of a number | Math.cos(x) |
exp(x) | Returns the value of Ex | Math.exp(x) |
floor(x) | Returns the value of a number rounded downwards to the nearest integer | Math.floor(x) |
log(x) | Returns the natural logarithm (base E) of a number | Math.log(x) |
max(x,y) | Returns the number with the highest value of x and y | Math.max(x,y) |
min(x,y) | Returns the number with the lowest value of x and y | Math.min(x,y) |
pow(x,y) | Returns the value of x to the power of y | Math.pow(x,y) |
random() | Returns a random number between 0 and 1 | Math.random() |
round(x) | Rounds a number to the nearest integer | Math.round(x) |
sin(x) | Returns the sine of a number | Math.sin(x) |
sqrt(x) | Returns the square root of a number | Math.sqrt(x) |
tan(x) | Returns the tangent of an angle | Math.tan(x) |
var stringScalar = 'a string'; |
var stringScalar = 'a string'; |
Property | Description | Syntax |
length | Returns the number of elements in a
string. |
stringLength = myString.length; |
Method | Description | Syntax
& Examples |
concat() | Concatenates string arguments to the
string on which the method was invoked. |
resultString = myStringObject.concat(string1,string2,...,stringX) |
charAt() | Returns the character at a specified position (this case index position) | char = myStringObject.charAt(index) |
charCodeAt() | Returns the code of a character specified by its position in a string | char_code = my_string.charCodeAt(char_position) |
indexOf() | Returns the position of the first
occurrence of a specified string value in a string or '-1' if the
'searchValue' is not found. The 'searchValue' can be a character or a
substring.
|
integerValue = myStringObject.indexOf(searchValue,[fromIndex]) |
lastIndexOf() | Returns the position of the last
occurrence of a specified string value, searching backwards from the
specified position in a string.
|
integerValue = myStringObject.lastIndexOf(searchValue,[fromIndex]) |
replace() | Replace the first occurence of 'findString'
substring of myStringObject with 'newString' and return the
modified 'myStringObject' on whitch the methods was invoked. If the
'findString' is not a substring, the returned result is the original
'myStringObject'.
|
resultString = myStringObject.replace(findString, newString) Example: "12345".replace("234","abc") = "1abc5" |
split() | The method splits myStringObject
into a series of substrings depending on delimiterString and max_substrings
parameters. The method returns an
array of the resulting substrings.
The 'delimiterString' parameter
is a substring that is used to
determine where to split the
string, and 'max_substrings'
is an integer value that specifies the
maximum number of resulting substrings.
|
resultString
= myStringObject.split(delimiterString,
[max_substrings]) Example: myString = "1:John"; var result1=myString.split(""); result1: ["1", ":", "J", "o", "h", "n"] var result2=myString.split("o",1); result2: ["1:J"] var result3=myString.split("oh",5); result3: ["1:J", "n"] |
substr() | Extracts a specified number of
characters in a string, from a start index. If the length
parameter is
omitted, then extract to the end of the string.
|
resultString =
myStringObject.substr(start,[length]) Example: "12345".substr(1,3)= "234" "12345".substr(1) = "2345" |
substring() |
Extracts a substring specified by first and last character position.
If the last character position is omitted, then extract to the end of
the string.
|
resultString
= myStringObject.substring(start, end) Note: the resultString's first charater is myStringObject(start), the last character is myStringObject(end-1) Examples: "12345".substring(1,4) = "234" "12345".substring(1) = "2345" |
toLowerCase() | Returns a string based on 'myStringObject' in lowercase letters | lowerCaseString = myStringObject.toLowerCase() |
toUpperCase() | Returns a string based on 'myStringObject' in uppercase letters | upperCaseString = myStringObject.toUpperCase() |
String.fromCharCode() | Returns a string consisting of one character with a specified code | my_char = String.fromCharCode(my_char_code) |
var regexpObject = new RegExp("pattern", "modifiers"); |
var regExp = /pattern/modifiers |
Method | Description | Syntax
& Examples |
match() | Returns an Array with the occurrence(s)
of a RegExp inside a string. If no substring can be extracted then
return null:
|
r = new RegExp("a.c","i"); s = "1ABC2abc".match(r) result: s will be ["ABC"] r = new RegExp("a.c","gi"); s = "1ABC2abc".match(r) result: s will be ["ABC"], ["abc"] |
search() | Return the index of the first occurrence
of a RegExp inside a string, or -1 if not found. Caution: while the 'search()' method is similar to the String's 'indexOf()' method, 'search()' only works with regular expressions, while the 'indexOf()' method does not accept a RegExp argument! |
index = "1aBc2".search(/A.C/i) result: index = 1 index = "1aBc2".search("a.c") result: index = 1 |
replace() | This is the String
object's 'replace()' method, and it
accepts a RegExp as parameter. |
r="aBcAbC".replace(/a/,"x") result: r="xBcAbC" r="aBcAbC".replace(/A/,"x") result: r="aBcxbc" r="aBcAbC".replace(/a/gi,"x") result: r="xBcxbC" |
split() | This is the String
object's 'split()' method, and it
accepts a RegExp as parameter.
|
r = "just/threeXwords".split(/[\/x]/i) result: r=["just","three","words"] |
var booleanObject = new Boolean(); |
var b1=new Boolean(0); // 0 is boolean false |
var booleanScalar = true; |
var numberObject = new Number(value); |
var numberScalar = 123; |
Properties (Constants) |
Description |
MAX_VALUE | The largest representable number |
MIN_VALUE | The smallest representable number |
NaN | Representing invalid numeric values ('not a number') |
NEGATIVE_INFINITY | Special positive infinite value; returned on overflow(it is returned when a calculation returns a negative number greater than the largest negative number in JavaScript) |
POSITIVE_INFINITY | Special negative infinite value; returned on overflow(It is returned when a calculation returns a positive number greater than the largest number in JavaScript) |
var month = 13; |
// If the result is less than or equal to MAX_VALUE, |
Method | Description | Syntax |
toExponential() | A string representation of number, in exponential notation, with one digit before the decimal place and aNumber digits after the decimal place | myNumber.toExponential(aNumber) Example: var n = 12345.6789; n.toExponential(5);// Returns 1.23457e+4 |
toFixed() | A string representation of number that does not use exponential notation and has exactly aNumber digits after the decimal place. | myNumber.toFixed(aNumber) Example: var n = 12345.6789; n.toFixed(1);// Returns 12345.7: note rounding |
toPrecision() | A string representation of number that contains aNumber significant digits | myNumber.toPrecision(aNumber) Example var n = 12345.6789; n.toPrecision(5);// Returns 12346: note rounding |
toString() | A string representation of the number. - base : between 2 and 36, represent the base in which the number should be represented. If omitted, base 10 is used |
myNumber.toString(base) |
functionObjectName = new Function ([arg1, arg2, ... argn], functionBody);
|
// the following line defines the function: myFuncObject(argument) { alert(argument) } |
var funcArgumentName = "argument"; |
Associativity | Operator | Operand type(s) | Operation performed |
L | + | String object only |
String concatenation |
L | == | object, object |
Test for equality |
L | != | object, object |
Test for inequality |
L | === | object, object |
Test for identity |
L | !== | object, object |
Test for non-identity |
R | ?: | object, any, any |
Conditional operator applied to
an object: selection depends on whether the object exists or is true,
vs it does not exist, or is false, or is empty String object |
R | = | object, object |
Assignement |
L | . | object, identifier | Property access |
L | [ ] | array, integer | Array index |
L |
[ ] |
object, string |
String index |
R | new | constructor call | Creates new object |
R | delete | lvalue | Undefine a property (unary) |
R | typeof | object | Return the object data type as a
string value |
L | instanceof | object, objectType |
Check object type |
L | in | string, object | Returns true if a property name string is a property of a specified object |
var d = new Date(); // Create a new object with the Date( ) constructor |
//Example 1 : |
var myObject = {x: 1, y: 2}; |
// Syntax : |
//Syntax: |
<html> |
<html> |
<head> |
<head> |
// Example 1: |
<html> |
<html> |
window.alert ("This is a message that is displayed in a pop-up window"); |
var confirmation = window.confirm (message); |
var userInput = window.prompt("Input some text here", "this is an initial text displayed in the entry field"); |
Syntax : |
//Example 1: |
// Example: |
// Example: |
onClick, onKeydown, onKeypress, |
<TAG [attributes] eventHandlerName="JavaScript Code"> |
<img src="myIcon.gif" onDoubleclick="javascript:alert('The image myIcon.gif has been double-clicked');" /> |
Event handler | Applies to (Browser object types) |
Occurs when |
onAbort | image | Occurs when the loading of an image process is aborted(for example when the user clicks on a link or on the 'Stop' button). |
onFocus | body, frameset, anchor, area, input, select, textarea, button | Occurs when an display object receives focus. It may be used with the same browser objects as onBlur event handler. |
onBlur | body, frameset, anchor, area, input, select, textarea, button | Occurs when the focus to the one of display object listed before is removed. |
onResize | Most of the elements that have a specifieble size (i.e. for which 'height' and 'width' can be defined) | Occurs when a resizable element changes its size. |
onClick | the most of browser object types | Occurs when the mouse device button is clicked over an display object. |
onChange | body, input, select, textarea | Occurs when a display object of 'form control' type loses the focus and its value has been modified since gaining focus. |
onDblclick | the most of browser object types | Occurs when the mouse device button is double-clicked over an display object. |
onKeydown | the most of browser object types | Occurs when a keyboard key is pressed down over an display object. |
onKeypress | the most of browser object types | Occurs when a keyboard key is pressed and released over an display object. |
onKeyup | the most of browser object types | Occurs when a keyboard key is released over an display object. |
onLoad | body, frameset, image |
Occurs when the browser finishes loading an image, an HTML document, or all the frames within a frameset. |
onUnload | body, frameset | Occurs when the browser removes an HTML document view or frame from a browser window. |
onMouseout | the most of browser object types | Occurs when the mouse device is moved away from an display object. |
onMouseover | the most of browser object types | Occurs when the mouse device is moved over an display object. |
onMousedown | the most of browser object types | Occurs when the mouse device button is pressed over an display object. |
onMouseup | the most of browser object types | Occurs when the mouse device button is released over an display object. |
onMousemove | the most of browser object types | Occurs when the mouse device is moved while it is over an display object. |
onReset | only to the form object | Occurs when a form display object is reseted(when the user clicks the 'Reset' button). |
onScroll | any scrollable container e.g. window, iframe Note: by using CSS one can create other scrollable containers apart from iframes |
Occurs when the documentin a container element is scrolled.
Note: this event cannot be attached directly in HTML to a window/frame; instead, a javascript function must explicitly attach it via e.g.: window.onScroll=scrollHandlerFunctionName(); |
onSelect | input-text, input-password, textarea | Occurs when the user selects some text in a text field display object. |
onSubmit | only to the form object | Occurs when a form display object is submitted(when the user clicks the 'Submit' button). |
<script> |
<head> |
// Display mouse coordinates as it moves in the browser status bar |
NS/Firefox Property |
Description | IE Equivalent |
altKey, ctrlKey, shiftKey | Boolean properties that indicate whether the Alt, Ctrl, Meta, and Shift keys were pressed at time of the event. | Same |
button | An integer indicating which mouse button was pressed or released, 0 = left, 2 = right, 1 = middle. | Same, but mouse events only work for left button. |
clientX, clientY | Returns the mouse coordinates at the time of the event relative to upper-left corner of the window. | Same |
screenX, screenY | Returns the coordinates of the mouse relative to the screen when the event fired. | Same |
type | A string indicating the type of event, such as "mouseover", "click", etc. | Same |
target | Returns a reference to the browser object that invoked the event. | srcElement |
which | Property indicating the Unicode for the key pressed, including the modifier keys (e.g. 'shift') | keyCode |
<html> |
<html> |
<html> |
// Syntax :
// Example : function myFunction(myStringArgument, myDateArgument) { ... } intervalID = window.setInterval(myFunction, 1000, "a string", new Date()); |
// Syntax : |
// Syntax : |
// Syntax : |
<html> |
Components.utils.reportError ("Message in the JavaScript error console"); |