Java Script
Java Script
Java Script
Basics
1. Introduction
JavaScript is the most widely used client-side programming language on the
web. It is:
• a small, lightweight, object-oriented, cross-platform, special-purpose
scripting language meant to be run under a host environment (typically
a web browser).
• a client-side scripting language to enrich web user-interfaces and
create dynamic web pages (e.g., form input validation, and immediate
response to user's actions).
• the engine that supports AJAX (Asynchronous JavaScript and XML), which
generate renew interest in JavaScript.
JavaScript, originally called LiveScript, was created by Brendan Eich at
Netscape in 1995. Soon after, Microsoft launched its own version of
JavaScript called JScript. Subsequently, Netscape submitted it
toECMA (formerly "European Computer Manufacturers Association", now "Ecma
International - European association for standardizing information and
communication systems") for standardization, together with Microsoft's
JScript.
The ECMA Specification is called "ECMA-262 ECMAScript Language
Specification" (also approved as "ISO/IEC 16262"):
• First Edition (June 1997)
• Second Edition (August 1998)
• Third Edition (December 1999)
• Forth Edition - abandon due to political differences
• Fifth Edition, 5.1 Edition (June 2011): not finalized, working draft
only.
Meanwhile, the Mozilla Project
(@ https://developer.mozilla.org/en/JavaScript) continues to upgrade the
JavaScript with these major versions:
• 1.0 (1996)
• 1.3 (1998): ECMA-262 1st edition compliance
• 1.5 (1999): ECMA-262 3rd edition compliance
• 1.6, 1.7:
2. Preparation
I shall assume that you know HTML and CSS (you cannot do JavaScript
without understanding HTML/CSS!). I shall also assume that you
understanding some programming basics (e.g., if-else, for-loop).
You need a text editor to write your JavaScript. You could use a plain
text editor such as NotePad. But to improve your productivity, a
good programming text editor is essential. There are many
freeware/shareware available, such as PSPad (www.pspad.com), NotePad++
(http://notepad-plus.sourceforge.net), TextPad (www.textpad.com)
(Read "Programming Text Editors"). You can also use a full-scale IDE such
as NetBeans or Eclipse, which provides content-assist (aka auto-complete)
feature that greatly enhances your productivity.
JavaScripts run inside a browser. There are many (too many!) standards
regarding JavaScript, none of the browser adheres to all the standards
strictly. Furthermore, browser often create their own extension. As the
behavior of JavaScript could be different in different browsers, I suggest
that you have the Internet Explorer (IE), Mozilla Firefox, and Google
Chrome for testing.
Let us write our first JavaScript to print the message "Hello, world".
Start with a new file and enter the following codes. Do not enter the line
numbers, which is used to aid in explanation. Take note that:
• JavaScript is case sensitive. A rose is NOT a ROSE and is NOT a Rose.
• "Extra" white spaces (blanks, tabs and newlines) are ignored. That is,
multiple white spaces is treated as a single blank character. You
could use them liberally to make your program easier to read.
Save the file as "JSEx1.html" (or any filename that you prefer, with file
extension of ".html" or ".htm"). Run the script by loading the HTML file
into a JavaScript-enabled browser.
" JSEx1.html "
1+
<html>+
2+
<head>+
3+
++<title>JavaScript+Example+1:+Functions+alert()+and+document.write()</title>+
4+
++<script:type="text/javascript">:
5+
::::alert("Hello,:world!");:
6+
::</script>+
7+
</head>+
8+
<body>+
9+
++<h1>My+first+JavaScript+says:</h1>+
10+
++<script:type="text/javascript">:
11+
::::document.write("<h2><em>Hello:world,:again!</em></h2>");:
12+
::::document.write("<p>This:document:was:last:modified:on:"::
13+
::::::::+:document.lastModified:+:".</p>");:
14+
::</script>+
15+
</body>+
16+
</html>+
Dissecting the Program
1. JavaScripts are programming codes that are embedded inside an HTML
document. The codes are contained between a pair
of <script> and </script> tags. The attribute type="text/javascript" in
the <script> start-tag identifies the scripting language, as follow:
2. <script+type="text/javascript">+
3. ++//+Your+JavaScript+programming+codes+here!+
</script>+
}+
3.4 Example 4: Loop
The following script prompts the user for a multiplier, and prints the
multiples of 1 to 100 using a for-loop.
" JSEx4.html "
1+
<html>+
2+
<head>+
3+
++<title>JavaScript+Example+4:+Loop</title>+
4+
</head>+
5+
<body>+
6+
++<h2>Testing+Loop</h2>+
7+
++<script:type="text/javascript">:
8+
::::var:multiplier:=:prompt("Enter:a:multiplier::");:
9+
::::for:(var:number:=:1;:number:<=:100;:number++):{:
10+
::::::document.writeln(number:*:multiplier);:
11+
::::}:
12+
::</script>+
13+
</body>+
14+
</html>+
Dissecting the Program
• Line 8 prompts the user for a number, and assigns it to the
variable multiplier.
• Lines 9-11 contain a for-loop. A for-loop takes the following syntax:
• for:(+initialization+;+test+;+post3processing+):{+
• +++body+;+
}+
Let's rewrite the example to place the HTML, CSS and JavaScript in three
different files.
" JSEx6a.html "
1+
<html>+
2+
<head>+
3+
++<title>JavaScript+Example+6a:+Separating+HTML,+CSS+and+JavaScript</title>+
4+
++<link+rel="stylesheet"+href="JSEx6a.css">+
5+
++<script+type="text/javascript"+src="JSEx6a.js"></script>+
6+
</head>+
7+
<body>+
8+
++<p>"Hello"+alert+Box+appears+<em>after</em>+the+page+is+loaded.</p>+
9+
++<p+id="magic">Point+your+mouse+pointer+here!!!</p>+
10+
++<p>Try+closing+the+window+or+refreshing+the+page+to+activate+the+"Bye"+alert+box.</p>+
11+
</body>+
12+
</html>+
" JSEx6a.css "
1+
.red+{+
2+
++color:red;+
3+
}+
" JSEx6a.js "
1+
window.onload+=+function()+{+
2+
+++init();+
3+
+++alert("Hello!");+
4+
}+
5+
++
6+
window.onunload+=+function()+{+
7+
+++alert("Bye!");+
8+
}+
9+
++
10+
function+init()+{+
11+
+++document.getElementById("magic").onmouseover+=+function()+{+
12+
++++++this.className+=+"red";+
13+
+++}+
14+
+++document.getElementById("magic").onmouseout+=+function()+{+
15+
++++++this.className+=+"";+
16+
+++}+
17+
}+
Dissecting the Program
1. Placing the scripting codes inside the HTML page is not a good
software engineering practice. Instead, the now-preferred approach is
to place the scripts, as well as CSS styles, in external files.
2. Let's begin with the HTML file. Now, the HTML file keeps only the
contents, no presentation style and no programming codes.
Notes: If you get the error "Script Panel was inactive during page load"
when switching into the "script" panel, you need to disable "private
browsing" in Firefox's Tools ⇒ Options ⇒ Privacy.
4.2 Other Browsers' add-on
• Safari: Web Inspector
• Google Chrome: Developer Tools
• IE: Internet Explorer Developer Tools
• Opera: Dragonfly
4.3 Aptana Studio
An open source IDE (based on Eclipse), which supports JavaScript and Ajax.
4.4 NetBeans
You can write JavaScripts by creating a web application under NetBeans
(Read "Developing web application under NetBeans"), via new ⇒ Others ⇒ In
"Categories", select "Other" ⇒ In "File Types", select "HTML File" or
"JavaScript File". NetBeans provides content-assist (aka auto-complete)
feature, which greatly improves your productivity.
Read "JavaScript Debugger User's Guide"
@ http://netbeans.org/kb/67/web/js-debugger-ug.html. But it is no longer
available for NetBeans 7.0.1. Use firebug instead.
4.5 Eclipse
[TODO]
1. JavaScripts enclosed between <script> and </script> runs when the the
page is loading.
2. Some JavaScripts run as a result of the user's or browser's action.
For example, clicking a button (onclick) or loaded a page (onload).
<script+type="text/javascript">+
...+Your+JavaScript+statements+here+...+
</script>+
<script+type="text/javascript">+
<!ee+
...+Your+JavaScript+statements+here+...+
//:ee>+
</script>+
5.2 <head> or <body> ?
You can place your JavaScript in either the HEAD section (called Header
Script) or BODY section (called Body Script) of an HTML document.
Typically, global variables and function definitions are placed in HEAD
section, which will always be loaded and available to be used by the
scripts in the BODY section. Remember that the HEAD section is loaded
before the BODY section. In short, HEAD section is preferred.
5.3 External JavaScript
The now-preferred approach is to keep the JavaScript in an external file
with file extension of ".js", and reference it via the scr (source)
attribute as follows:
<script+type="text/javascript"+scr="JavaScriptFilename.js"></script>+
Note: You always need the end-tag </script>. The standalone tag <script+ ...+
/> does not work?!
A end-of-line comment begins with // and lasts till the end of the current
line. A multi-line comment begins with /* and lasts till */. Recall that
HTML comments are enclosed inside <!__ and __>.
6.2 Expression
An expression is a combination of variables, literals, operators, and sub-
expressions that can be evaluated to produce a single value.
6.3 Statement & Block
A statement is a single instruction consisting of operators, variables and
expression. It is strongly recommended to end each statement with a semi-
colon (;) (although it is not strictly necessary as the new-line can also
serve as the statement terminator in JavaScript).
A block consists of zero or more statements enclosed in a pair of curly
braces {+...+}. No semi-colon is needed after the closing brace.
6.4 Variables, Literals & Types
Variables & Assignment Operator '='
A variable is a named storage location that holds a value,
e.g., sum, average, name, message.
• A variable name (aka identifier) consists of letters (a-z, A-Z),
digits (0-9), underscore (_); and must begin with a letter or
underscore.
• JavaScript is case sensitive. A ROSE is not a rose and is not a Rose.
• A variable is declared using keyword var.
• You can assign (and re-assign) a value to a variable using the
assignment '=' operator.
Literals
A literal is a fixed value, e.g., 5566, 3.14, "Hello", true, that can be
assigned to a variable or form part of an expression.
Types
JavaScript supports the following primitive types:
• String: contains texts. Strings literals are enclosed in a pair of
single quotes or double quotes (e.g., "Hello", 'world').
• Number: takes an integer (e.g., 5566) or a floating-point number
(e.g., 3.14159265).
• Boolean: takes a literal value of either true or false (in lowercase).
• undefined: takes a special literal value called undefined.
JavaScript is object-oriented and supports the Object type and null (un-
allocated object). Furthermore, function is also a type in JavaScript.
These types will be discussed later.
Unlike most of the general programming languages (such as Java, C/C++ and
C#) which are strongly type, JavaScript is loosely type (similar to most
of the scripting languages such as UNIX Shell Script and Perl). You do not
have to explicitly declare the type of a variable (e.g., int, float,
string) during declaration. The type is decided when a value is assigned
to that variable. If a number is assigned, the variable takes Number type
and can perform numeric operations such as addition and subtraction. If a
string is assigned, the variable takes String type and can perform string
operating such as string concatenation.
undefined type and undefined value
An undeclared variable has a special type called undefined. You cannot
refer to its value.
When a variable is declared without assigning an initial value, it takes
the type undefined and holds a special value
called undefined (uninitialized is probably more precise?!), As soon as a
value is assigned, the variable takes on the type of that value. The act
of putting a value into a variable sets its type. You can change the type
of a variable by re-assigning a value of another type. Types are converted
automatically as needed during execution (known as dynamically-typed).
Operator " typeof "
You can use the operator typeof to check the type of a variable.
Example
document.writeln("<p>Type+is+"+++typeof+magic+++"</p>");++//+not+declared+
++
var+magic;++++++//+Declare+a+variable+
document.writeln("<p>Type+is+"+++typeof+magic+++",+value="+++magic+++"</p>");+
++++
magic+=+55;+++++//+Assign+an+integer+
document.writeln("<p>Type+is+"+++typeof+magic+++",+value="+++magic+++"</p>");+
document.writeln("<p>Result="+++(magic+/+3)+++"</p>");+//+Arithmetic+operation+
++++
magic+=+55.66;++//+Assign+a+floating_point+number+
document.writeln("<p>Type+is+"+++typeof+magic+++",+value="+++magic+++"</p>");+
++++
magic+=+'Hello';+//+Assign+a+string+
document.writeln("<p>Type+is+"+++typeof+magic+++",+value="+++magic+++"</p>");+
document.writeln("<p>Result="+++(magic+/+3)+++"</p>");+++
+++
magic+=+"3.14";++//+This+is+also+a+string+
document.writeln("<p>Type+is+"+++typeof+magic+++",+value="+++magic+++"</p>");+
document.writeln("<p>Result="+++(magic+/+3)+++"</p>");+
+++
magic+=+false;+++//+Assign+a+boolean+
document.writeln("<p>Type+is+"+++typeof+magic+++",+value="+++magic+++"</p>");+
++++
magic+=+new+Date();++//+Assign+an+object+(to+be+discussed+later)+
document.writeln("<p>Type+is+"+++typeof+magic+++"</p>");++//+object+
Constants
You can create a read-only, named constant with the keyword const (in
place of var). For example,
const+SIZE+=+9;+
Example,
<script+type="text/javascript">+
++//+Comparing+numbers+
++var+x+=+8;+
++document.writeln(x+==+8);++++//+true+(same+value)+
++document.writeln(x+==+"8");++//+true+(string+converted+to+number)+
++document.writeln(x+===+8);+++//+true+(same+type+and+value)+
++document.writeln(x+===+"8");+//+false+(different+type)+
++++
++document.writeln(x+<+10);++++//+true+
++document.writeln(x+<+"10");++//+true+(string+converted+to+number)+
+++
++//+Comparing+two+strings+
++document.writeln("8"+<+"10");+++++//+false+(comparing+two+strings+alphabetically)+
++document.writeln("8"+<+"9");++++++//+true+(comparing+two+strings,+not+numbers)+
++document.writeln("Hello"+<+"hi");+//+true+(comparing+two+strings)+
</script>+
Logical Operators
Syntax
if:(condition):{+ if+(day+===+'sat'+||+day+===+'sun')+{+
++trueBlock;:
}+ +++alert('Super+weekend!');+
}+
if:(condition):{+ if+(day+===+'sat'+||+day+===+'sun')+{+
++trueBlock;:
}:else:{+ +++alert('Super+weekend!');+
++falseBlock;: }+else+{+
}+
+++alert('It+is+a+weekday...');+
}+
variable+=:(condition):?+trueValue::+ var+max+=+(a+>+b)+?+a+:+b;+
falseValue;+
Same+as+ var+abs+=+(a+>=+0)+?+a+:+_a;+
if+(condition)+{+variable+=+trueValue;+}+
else+{+variable+=+falseValue;+}+
if:(condition1):{+ if+(day+===+'sat'+||+day+===+'sun')+{+
++block1;::
}:else:if:(condition2):{+ +++alert('Super+weekend!');+
++block2;: }+else+if+(day+===+'fri')+{+
}:else:if:(...):{+
......+ +++alert("Thank+God,+it's+friday!");+
}:else:{+ }+else+{+
++elseBlock;:
}+ +++alert('It+is+a+weekday...');+
}+
switch:(expression):{: switch+(day)+{+
::case+value1:+
++++statements;:break;: +++case+'sat':+case+'sun':++
::case+value2:+ ++++++alert('Super+weekend!');+break;+
++++statements;:break;+
++......+ +++case+'mon':+case+'tue':+case+'wed':+case+'thu'
++......+ ++++++alert('It+is+a+weekday...');+break;+
++default:+
++++statements;: +++case+'fri':++
}+
++++++alert("Thank+God,+it's+Friday");+break;+
+++default:++
++++++alert("You+are+on+earth?!+Aren't+you?");+
}+
6.11 Loops
JavaScript provides the following loop constructs. The syntax is the same
as Java/C/C++.
Syntax
while:(test):{+ var+sum+=+0,+number+=+1;+
++trueBlock;:
}+ while+(number+<=+100)+{+
+++sum++=+number;+
}+
do:{+ var+sum+=+0;+number+=+1;+
++trueBlock;:
}:while:(test);+ do+{+
++sum++=+number;+
}+
for:(initialization;+test;+post3processing):{+ var+sum+=+0;+
++trueBlock;:
}+ for+(var+number+=+1;+number+<=+100;+number++)+
+++sum++=+number;+
}+
A function accepts zero or more arguments from the caller, performs the
operations defined in the body, and returns zero or a single result to the
caller.
function+functionName(argument1,+argument2,+...):{+
++statements;+
++......+
++return+value;+
++......+
}+
Functions are declared using the keyword function. You do not have to
specify the return-type and the types of the arguments because JavaScript
is loosely typed. You can use a return statement to return a single piece
of result to the caller anywhere inside the function body. If
no return statement is used (or a return with no value), JavaScript
returns undefined. Functions are generally defined in the HEAD section, so
that it is always loaded before being invoked.
To invoke a function, use functionName(argument1,+argument2,+...).
Example:
<html>+
<head>+
<title>Function+Demo</title>+
<script+type="text/javascript">+
++function+add(item1,+item2)+{+++++++++++++++++//+Take+two+numbers+or+strings+
+++++return+parseInt(item1)+++parseInt(item2);+//+Simply+item1+++item2+won't+work+for+
strings+
++}++
</script>+
</head>+
<body>+
<script+type="text/javascript">+
++var+number1+=+prompt('Enter+the+first+integer:');++//+returns+a+string+
++var+number2+=+prompt('Enter+the+second+integer:');+//+returns+a+string+
++alert('The+sum+is+'+++add(number1,+number2));+
</script>+
</body>+
</html>+
Function has access to an additional variable called arguments inside its
body, which is an array (to be discussed in full later) containing all the
arguments. For example,
<html>+
<head>+
<title>Function+Demo</title>+
<script+type="text/javascript">+
++function+add()+{+
++++var+sum+=+0;+
++++for+(var+i+=+0;+i+<+arguments.length;+i++)+{+
++++++sum++=+parseFloat(arguments[i]);+
++++}+
++++return+sum;+
++}+
</script>+
</head>+
<body>+
<script+type="text/javascript">+
++document.write(add(1,+2,+3,+4,+5)+++"<br+\>");+
++document.write(add(1,+2)+++"<br+\>");+
++document.write(add(1.1,+"2.2")+++"<br+\>");+
</script>+
</body>+
</html>+
Primitive arguments are passed by value. That is, a copy of the variable
is made and passed into the function.
6.13 Interacting with Users
JavaScript provides these built-in top-level functions for interacting
with the user:
• alert(string): Pop-up a box to alert user for important information. The
user will have to click "OK" to proceed. alert() returns nothing
(or undefined).
• prompt(string,+defaultValue): Pop-up a box to prompt user for input, with
an optional defaultValue. prompt() returns the user's input as a string.
For example,
• var+number1+=+prompt('Enter+the+first+integer:');+
• var+number2+=+prompt('Enter+the+second+integer:');+
• alert('The+sum+is+'+++number1+++number2);+++++++++++++++++++++++//+Concatenate+
two+strings+
}+
parseFloat('Hi');++++//+gives+NaN+
<html>+
<head>+
<title>Event+Demo</title>+
<script+type="text/javascript">+
++function:say(message):{:
:::::alert(message);:
::}+
</script>+
</head>+
<body>+
++<h2+onmouseover="this.style.color='red'"+
++++++onmouseout="this.style.color=''">Hello</h2>+
++<input+type="button"+value="click+me+to+say+Hello"+onclick="say('Hello')">+
++<p+onclick="say('Hi')">This+paragraph+can+say+Hi...</p>+
</body>+
</html>+
function+f1(a1,+a2,+a3)+{+
++document.writeln("<p>a1:+type+is+"+++typeof+a1+++",+value="+++a1+++"</p>");+
++document.writeln("<p>a2:+type+is+"+++typeof+a2+++",+value="+++a2+++"</p>");+
++document.writeln("<p>a3:+type+is+"+++typeof+a3+++",+value="+++a3+++"</p>");+
}+
+
f1('hello');+
//+a1:+type+is+string,+value=hello+
//+a2:+type+is+undefined,+value=undefined+
//+a3:+type+is+undefined,+value=undefined+
+
f1(1,+2);+
//+a1:+type+is+number,+value=1+
//+a2:+type+is+number,+value=2+
//+a3:+type+is+undefined,+value=undefined+
+
f1('hello',+1,+2);+
//+a1:+type+is+string,+value=hello+
//+a2:+type+is+number,+value=1+
//+a3:+type+is+number,+value=2+
You can use this feature to provide default value to function argument,
for example,
function+f2(a1,+a2,+a3)+{+
++if+(a2+===+undefined+||+a2+===+null)+a2+=+88;+
++a3+=+a3+||+'default';+++//+same+as+above,+but+more+concise+
++document.writeln("<p>a2:+type+is+"+++typeof+a2+++",+value="+++a2+++"</p>");+
++document.writeln("<p>a3:+type+is+"+++typeof+a3+++",+value="+++a3+++"</p>");+
}+
+
f2('hello');+
//+a2:+type+is+number,+value=88+
//+a3:+type+is+string,+value=default+
+
f2('hello',+null,+null);+
//+a2:+type+is+number,+value=88+
//+a3:+type+is+string,+value=default+
In the above example, we allow caller to omit the trailing arguments (a2,
a3) or pass a null value (which is a special literal for unallocated
object). The common idiom in practice is to use the short-circuited OR
expression (as in a3) to provide default value if no value (undefined or
null) is passed, provided the valid inputs cannot be false, 0, '', etc,
that evaluated to false.
7. Objects
JavaScript is object-oriented. It, however, does not support all the OO
features, so as to keep the language simple.
JavaScript's OO is prototype-based, instead of class-based. A class-
based OO language (such as Java/C++/C#) is founded on concepts
of class and instance. A class is a blue-print or prototype of things of
the same kind. An instance is a particular realization (instantiation,
member) of a class. For example, "Student" is a class; and "Tan Ah Teck"
is an instance of the "Student" class. In a class-based OO language, you
must first write a class definition, before you can create instances based
on the class definition.
A prototype-based OO language (such as JavaScript) simply has objects (or
instances). It uses a prototype as a template to get the initial
properties of a new object. In JavaScript, you do not have to define a
class explicitly. Instead, you define a constructor method to create
objects (or instances) with a set of initial properties. Furthermore, you
can add or remove properties of an object at runtime, which is not
permitted in class-based OO languages.
7.1 Properties and Methods
An object is a collection of properties and methods under a common name:
For example, a Car object has properties such as make, price, capacity; and
methods such as startEngine(), move(), brake(), stopEngine().
7.2 The dot operator
Recall that an object is collection of properties and methods, under a
common name. You can use the dot (.) operator to access an underlying
property or invoke a method for a particular object, in the form
of anObjectName.aPropertyName, oranObjectName.aMethodName(arguments).
7.3 Constructor & the " new " Operator
A constructor is a special method that is used to create and initialize an
object. You can invoke the constructor with the operator "new" to create a
new object.
For example, JavaScript provide a built-in object called Date, having a
constructor method called Date(), you can invoke the Date() constructor to
create new Date instance as follows:
var+ now+ =+ new+ Date();+ + //+ Create+ a+ new+ object+ called+ now+ by+ calling+ constructor+
Date()+
now.getMonth();++++++++//+Invoke+getMonth()+method+for+the+Date+object+now.+
now.setYear(8888);+++++//+Invoke+setMonth()+method+for+the+Date+object+now.+
document.write(days.length);+++//+7+
13. var+anotherDays+=+["sun",+"mon",+"tue",+"wed",+"thu",+"fri",+"sat"];+
document.write(anotherDays.length);++//+7+
You can access individual element of an array via an index number, in the
form of anArrayName[index]. The index of the array begins at 0. You can use
the built-in property length to retrieve the length of the array.
var+days+=+['sun',+'mon',+'tue',+'wed',+'thu',+'fri',+'sat'];+
document.write("<p>"+++days[0]);+
for+(var+i+=+1;+i+<+days.length;+i++)+{+
+++document.write("+|+"+++days[i]);+
}+
document.write("</p>");+
++//+<p>sun+|+mon+|+tue+|+wed+|+thu+|+fri+|+sat</p>+
Array's Length
The JavaScript array's size is dynamically allocated. You can add more
elements to an array. You can also remove the content of an element using
keyword delete. The element becomes undefined. For example,
var+days+=+["sun",+"mon",+"tue"];+
document.writeln(days.length);++//+3+
document.writeln(days);+++++++++//+sun,mon,tue+
days[5]+=+"fri";++++++++++++++++//+Dynamically+add+an+element+
document.writeln(days.length);++//+6+
document.writeln(days);+ + + + + + + + + //+ sun,mon,tue,,,fri+ (elements+ in+ between+ are+
undefined)+
delete+days[2];+++++++++++++++++//+Remove+the+content+of+an+element+
document.writeln(days.length);++//+6+
document.writeln(days);+++++++++//+sun,mon,,,,fri+
days[days.length]+=+"sat";++++++//+Append+at+the+end+
document.writeln(days);+++++++++//+sun,mon,,,,fri,sat+
for..in loop
JavaScript provides a special for..in loop to process all the elements in
an array. The syntax is as follows, where index takes on the each of the
index number of element which are not undefined.
for:(var+index+in+arrayName)+{+...+}+
For example,
var+months+=+["jan",+"feb"];+
months[11]+=+"dec";+
for+(var+i+in+months)+{+
+++document.writeln(index+++":"+++months[i]+++",+");+
}+++//+0:jan,+1:feb,+11:dec,+
Array's Properties and methods
The Array object has these commonly-used properties:
• length: number of items.
fruits.join("|");++//+gives+"apple|orange|banana"+
For example,
var+str1+=+'Hello';++++++++++++++//+Assign+a+string+literal+
document.writeln(typeof+str1);+++//+Type+is+string+(primitive)+
var+str2+=+new+String('Hello');++//+String+object+constructor+
document.writeln(typeof+str2);+++//+Type+is+object+
Commonly-used properties:
• length: the number of characters in the string.
Commonly-used methods:
• indexOf(aChar,+fromIndex): returns the index of the character aChar,
starting from index fromIndex. The first character has index of 0.
• charAt(index): returns the character at the index position.
• substring(beginIndex,+endIndex): returns the substring
from beginIndex to endIndex (exclusive).
• lastIndexOf(aChar,+fromIndex): scans backward.
• split(delimiter): returns an array by splitting the string
using delimiter.
• toUpperCae(), toLowerCase(): returns the uppercase/lowercase string.
• new+Date(): constructs a Date object with the current date and time.
• new+ Date("Month,+ day,+ year+ hours:minutes:seconds"): constructs a Date object
with the the given time string.
• new+Date(year,+Month,+day): where month is 0-11 for Jan to Dec.
• new+Date(year,+Month,+day,+hours,+minutes,+seconds)
Commonly-used methods:
• getDate(), setDate(), getMonth(), setMonth(), getFullYear(), setFullYear():
get/set the date (1-31), month (0-11 for Jan to Dec), year (4-digit
year).
• getDay(): get the day of the week (0-6 for Sunday to Saturday).
• getHours(), setHours(), getMinutes(), setMinutes(), getSeconds(), setSeconds():
get/set the hours/minutes/seconds.
• getTime(), setTime(): get/set the number of milliseconds since January 1,
1970, 00:00:00.
8.7 Math Object
Commonly-used properties:
Commonly-used methods:
• abs(x)
• sin(a), cos(a), tan(a), asin(x), acos(x), atan(x), atan2(x,y)
• cell(x), floor(x), round(x)
• exp(x), log(x), pow(base,exp), sqrt(x)
• max(x,y), min(x,y)
• random(): returns a pseudo-random number between 0 and 1.
8.8 Function Object
Every function in JavaScript is actually a Function object. A variable can
be assigned a Function object, which will take the type function.
For example,
function+sayHello()+{+return+"Hello";+}++//+Define+a+'named'+function+
document.writeln(sayHello());++++++++++++//+Invoke+function+with+function+name+
document.writeln(typeof+sayHello);+++++++//+Type+is+function+
+++++
var+magic+=+sayHello;+++++++++++//+Assign+to+a+function+object+(without+parentheses)+
document.writeln(typeof+magic);+//+Type+is+function+
document.writeln(magic());++++++//+Invoke+function+
var+magic+=+function()+{+return+"Hello"+};+
Besides using function keyword, you can also use the Function constructor
(with new operator) to define a Function object (which is not easily
understood and not recommended).
magic+=+new+Function("arg1",+"arg2",+"return+arg1+++arg2");+
document.writeln(magic(55,+66));+
document.writeln(typeof+magic);+++++++//+Type+function+
++++
//+same+as+
function+magic(arg1,+arg2)+{+return+arg1+++arg2;+}+
document.writeln(magic(55,+66));+
this.getArea+=+function()+{+return+this.radius+*+this.radius+*+Math.PI;+};+
this.getArea+=+new+Function("return+this.radius+*+this.radius+*+Math.PI");+
The name and value are separated by ':'. The name-value pairs are
separated by commas. There is no comma after the last name-value pair.
For example:
//+Create+an+object+via+object+literal+
var+circle+=+{+
+++radius:+5.5,+
+++dateCreated:+new+Date(),+
+++getArea:+ function()+ {+ return+ this.radius*this.radius*Math.PI;+ },+ + //+ inline+
function+
+++toString:+circleDescription+
}+
++++
//+Define+method+
function+circleDescription()+{+
+++return+"Circle+with+radius="+++this.radius++
+++++++++++"+created+on+"+++this.dateCreated;+
}+
++++++++
//+Invoke+method+using+the+dot+operator+
document.writeln("<p>"+++circle+++",+Area="+++circle.getArea()+++"</p>");+
Object literal has gained popularity over the past few years (over the
procedural approach). A subset of the object literal called JSON
(JavaScript Object Notation) has become one of the most common data
formats for Ajax.
Operator " delete "
You can remove a property or a method from an object via operator delete.
Operator " instanceOf "
You can use the instanceOf operator to check if a particular instance
belongs to a particular class of objects, e.g.,
var+now+=+Date();+
now+instanceOf+Date;++//+gives+true;+
Operator " in "
You can use the in operator to check if a particular property belongs to
an object, for example,
"PI"+in+Math;+++++++++//+gives+true+
Loop for...in
Example [TODO]
Loop with
Example [TODO]
9.3 Property prototype
All the JavaScript objects have a special property called prototype, that
can be used to add property or method dynamically after the object is
defined (via a constructor or an initializer). The added property/method
will be available to all the new objects. For example,
//+Circle+constructor+
function+Circle(radius)+{+
+++this.radius+=+radius+||+1.0;+
+++this.getArea+=+function()+{+return+this.radius+*+this.radius+*+Math.PI;+};+
}+
++++++++
//+Define+more+property+and+method+
Circle.prototype.getCircumference+=+function()+{+return+2+*+this.radius+*+Math.PI;+};+
Circle.prototype.color+=+"green";+
+++
//+Create+a+Circle+and+invoke+property/methods+
var+circle1+=+new+Circle(1.5);+
document.writeln(circle1.getArea());+
document.writeln(circle1.getCircumference());+
document.writeln(circle1.color);+
//+Construct+an+Array+object+
var+months+=+new+Array('jan',+'feb',+'mar');+
document.writeln(months.constructor);++//+Array()+
document.writeln(months);++++++++++++++//+jan,feb,mar+
++++
//+Create+another+Array+object+by+invoking+the+constructor+of+the+first+object.+
var+days+=+months.constructor('mon',+'tue',+'wed')+
document.writeln(days);+++++++++++++++//+mon,tue,wed+
9.5 Associative Array?
An associative array is an array of key-value pair. Instead of using
numbers 0, 1, 2, ... as key as in the regular array, you can use anything
(such as string) as key in an associative array.
var+student+=+new+Array();+
+
student['name']+++=+'Peter';+
student['id']+++++=+12345;+
student['gender']+=+'male';+
+
document.writeln("<p>Name+is+"+++student['name']+++"</p>");+
document.writeln("<p>ID+is+"+++student['id']+++"</p>");+
document.writeln("<p>Gender+is+"+++student['gender']+++"</p>");+
However, if you check the array's length, via student.length, you get 0!?
JavaScript does not really support associative array, but allow you to add
properties to an object, using the associative array syntax. In other
words,
student.age+=+21;+++//+same+as+student[age]+=+21+
document.writeln("<p>Age+is+"+++student['age']+++"</p>");+
var+student+=+{'name':'peter',+'id':12345,+'gender':'male'};+
+
for+(key+in+student)+{+
+++document.writeln("<p>"+++key+++"+is+"+++student[key]+++"</p>");+
}+
Function Description
document.getElementById(anId)+ Returns the element with the given unique id.
var+elms+=+document.getElementsByTagName("*");+
for+(var+i+=+0;+i+<+elms.length;+i++)+{+
+++document.writeln("<p>"+++elms[i].value+++"</p>");+
+++.......+
}+
The above functions select element(s) based on the unique id, name attribue
and tag-name. HTML 5 further defines two function that can select elements
based on class attribute (which is used extensively by CSS in the class-
selector):
Function
document.querySelector(aClassName)+ Returns the first element with
document.querySelectorAll(aClassName)+ Returns an array of elements
Beside the above selection functions, there are many other selection
functions available. However, I strongly recommend that you stick to the
above functions. I listed below the other function below for completeness.
1. document.images returns an array of all <img> elements, same
as document.getElementsByTagName("img").
2. document.forms: return an array of all <form> elements.
3. document.links and document.anchors: return all the hyperlinks <a+
href=...> and anchors <a+name=...> elements. [To confirm!]
10.2 Manipulating Element's Content thru the
" innerHTML " Property
You can access and modify the content of an element via the "innerHTML"
property, which contains all the texts (includes nested tags) within this
element.
For example,
<p+id="magic">Hello,+<em>Paul</em></p>+
<script+type="text/javascript">+
++var+elm+=+document.getElementById("magic");+
++//+Read+content+
++alert(elm.innerHTML);++++//+Hello,+<em>Paul</em>+
++//+Change+content+
++elm.innerHTML+=+"Good+day,+<strong>Peter</strong>";+
++alert(elm.innerHTML);++++//+Good+day,+<strong>Peter</strong>+
</script>+
<html>+
<head>+
++<title>DOM+Tree</title>+
</head>+
<body>+
++<h2+onmouseover="this.style.color='red'"+
++++++onmouseout="this.style.color=''">Testing</h2>+
++<p>welcome+to+<i>JavaScript</i>...</p>+
</body>+
</html>+
Load the web page onto Firefox, and use the firebug to inspect the DOM
tree.
<html>+
<head>+
<title>DOM+Tree</title>+
<script+language="JavaScript">+
++function:printNode(node):{:
::::document.writeln("Node:name=":+:node.nodeName:+:",:value=":+:node.nodeValue:+:",:
type=":+:node.nodeType:+:"<br:/>");:
::::if:(node.hasChildNodes()):{:
::::::var:childs:=:node.childNodes;:
::::::for:(var:i:=:0;:i:<:childs.length;:i++):{:
::::::::printNode(childs[i]);:
::::::}:
::::}:
::}+
</script>+
</head>+
<body+onload="printNode(document.body)"><h2+onmouseover="this.style.color='red'"+
++onmouseout="this.style.color=''">Testing</h2><p>welcome+ to+
<i>JavaScript</i>...</p></body>+
</html>+
Node+name=BODY,+value=null,+type=1+
Node+name=H2,+value=null,+type=1+
Node+name=#text,+value=Testing,+type=3+
Node+name=P,+value=null,+type=1+
Node+name=#text,+value=welcome+to+,+type=3+
Node+name=I,+value=null,+type=1+
Node+name=#text,+value=JavaScript,+type=3+
Node+name=#text,+value=...,+type=3+
Accessing the HTML element via Node interface may not be too useful nor
practical for JavaScript applications, as you need to know the actual
topological structure of the DOM-tree. Furthermore, some browsers (e.g.,
firefox) may create extra Text nodes to contain the white spaces between
tags.
10.4 Text Node
DOM models the texts enclosed by HTML tags as a separate text node. It
cannot have child node. To retrieve the text content, you could the
property nodeValue. For example,
<p+id="magic">Hello</p>+
......+
alert(document.getElementById("magic").firstChild.nodeValue);+
document.getElementById("magic").firstChild.nodeValue+=+"Hi";++//+text+change+to+"Hi"+
10.5 Attribute Properties
To access an attribute of an Element node called elementName, you could
either use:
• property elementName.attributeName, where attributeName is the name of the
attribute, or
• methods elementName.getAttribute(name) and elementName.setAttribute(name,+value
).
For example,
<html>+
<head><title>Test+Attributes</title></head>+
<body>+
++<p+id="magic1"+align="left">Hello</p>+
++<p+id="magic2"+align="center">Hello,+again.</p>+
+++
++<script+type=text/javascript>+
++++var+node:=:document.getElementById("magic1");+
++++document.writeln(node.align);+++//+Get+attribute+"align"+
++++node.align+=+"center";++++++++++//+Set+attribute+"align"+to+a+new+value+
+++
++++node:=:document.getElementById("magic2");+
++++document.writeln(node.getAttribute("align"));++//+Read+attribute+"align"+
++++node.setAttribute("align",:"right");+++++++++++//+Write+attribute+"align"+
++</script>+
</body>+
</html>+
10.6 Attribute style (for CSS)
Element has a property called style, which models CSS style with CSS
properties such as color and textAlign. For example,
<p+id="magic">Hello</p>+
......+
document.getElementById("magic1").style.color="green";+
document.getElementById("magic1").style.textAlign="right";+
<body>+
<p+id="magic">Hello</p>+
<script+type="text/javascript">+
++alert(document.getElementById("magic").innerHTML);+
++var+newElm+=+document.createElement("p");+
++newElm.appendChild(document.createTextNode("Hello,+again"));+
++document.body.appendChild(newElm);+
</script>+
</body>+
<body>+
<p+id="magic">Hello</p>+
<script+type="text/javascript">+
++var+magicElm+=+document.getElementById("magic");+
++alert(magicElm.innerHTML);+
++var+newElm+=+document.createElement("p");+
++newElm.appendChild(document.createTextNode("Hello,+again"));+
++document.body.insertBefore(newElm,:magicElm);+
</script>+
</body>+
Replacing a Node ( replaceChild() )
Change the last line to document.body.replaceChild(newElm,+magicElm).
Deleting a Node ( removeChild() )
You can remove a child node from a parent node
via aParentNode.removeChild(aChildNode).
For example, let remove the last <p> from <body>.
<body>+
<p>Hello+1</p>+
<p>Hello+2</p>+
<p+id="magic">Hello+3</p>+
<script+type="text/javascript">+
++var+elm+=+document.getElementById("magic");+
++alert(elm.innerHTML);+
++document.body.removeChild(elm);+
</script>+
</body>+
<!__+Event+handler+calls+built_in+functions+__>+
<body+onload="alert('welcome')":onunload="alert('bye')">+
++++
<!__+Event+handler+calls+a+user_defined+function+__>+
<script+language="javaScript">+
++function+myHandler(event)+{+
++++alert(event);+
++}+
</script>+
<input+type="button"+value="click+me"+onclick="myHandler()"+/>+
++++
<!__+Event+handler+composes+of+JavaScript+statement(s)+__>+
<h1+onmouseover="this.style.color='red';:this.style.backgroundColor='black'":
::::onmouseout="this.style.color='';:this.style.backgroundColor=''">Hello</h1>+
[To Check]
11.3 The Event object
The event handlers are passed one argument, an Event object, which
described the event and its current states. You can use it to determine
where an event originated from and where it currently is in the event
flow.
The following properties are available to all the Event object:
• type: A string indicating the type of event, e.g., "click",
"mouseover".
• eventPhase: integer 1 for captured, 2 for at the target, and 3 for
bubbling phase.
Mouse-Related Events
Including click, mouseup, mousedown, mouseover, mouseout, mousemove. For mouse-
related events, the Event object provides these additional properties:
• button: integer 1 for left button, 2 for middle, and 3 for right
• clientX, clientY: mouse location relative to the client area.
• screenX, screenY: mouse location relative to the screen.
• altKey, ctrlKey, metaKey, shiftKey: boolean value indicating where these
key was pressed when the mouse event is fired.
Key-Related Events
Including keyup, keydown and keypress. For key-related events,
the Event object provides these additional properties:
• keyCode: ASCII code of the key pressed.
• altKey, ctrlKey, metaKey, shiftKey: boolean flag indicating whether these
key was also pressed.
• clientX, clientY: mouse location relative to the client area.
• screenX, screenY: mouse location relative to the screen.
11.4 Adding Event Listener
You can also add/remove event listener to tags, using the following
methods:
element.addEventListener(eventType,+functionName,+useCapture);N
element.removeEventListener(eventType,+functionName,+useCapture);+
For example,
<p+id="magic">Hello</p>+
......+
<script+type="text/javascript">+
++var:element:=:document.getElementById("magic");:
::element.addEventListener('mouseover',: function(): {: this.style.color='green';: },:
false);:
::element.addEventListener('mouseout',:function():{:this.style.color='';:},:false);+
</script>+
Event listeners can be added to any node, even text nodes (which you could
not assign event handlers to as they have no attributes).
There are two phases of event flow: a capture phase followed by a bubbling
phase.
1. Event Capture phase: The event first flows down from the document
root to the target element that trigger the event.
2. Event Bubbling phase: the event then bubbles up from the target
element to its parent node, all the way back to the document root.
For each event type, you could define a event handler for the capture
phase (triggered as event flows down from the root to the target element),
and another event handler for the bubbling phase (triggered when the event
bubble up from the target element to the root).
Example: [TODO]
[TO CHCEK]
12.2 The window object
The window object represents an open window in a browser. It is the top-
level object in the JavaScript hierarchy. All top-level properties and
methods such as alert(), prompt(), parseInt() belongs to the window object.
The window object is also the default object. That is, alert() is the same
as window.alert(). A window object is created automatically with
every <body> or <frameset> tag.
[TODO]
2. var+identifier+=+/[a_zA_Z_][a_zA_Z_]*/;+
3. var+integer+=+/[1_9][0_9]*|0/;+
var+imageFile+=+/\w+\.(jpg|gif|png)/i;+
5. var+pattern+=+new+RegExe("[1_9][0_9]*|0");+
Modifier: You can use modifier "g" to perform a global search (return
all matches instead of the first match), and "i" for case-insensitive
matching, as shown in the above example.
Back References: You can use $1 to $99 to refer to the back references
(within a string), or Regexe.$1 to Regexe.$99 object properties.
var+pattern+=+/(\S+)\s+(\S+)/;+
var+input+=+"Hello++world";+
input+=+input.replace(pattern,+"$2+$1");+
++//+result+is+"world+Hello"+
var+pattern+=+/<code>(.*?)<\/code>/g;+
++//+?+(after+*)+curb+greediness;+g+modifier+for+global+match+
var+input+=+"<code>first</code>+and+<code>second</code>";+
input+=+input.replace(pattern,+"$1");+
++//+result+is+"first+and+second"+
++//+If+greedy+is+used+(remove+the+?),++
++//+++result+is+"first</code>+and+<code>second"+
13.3 JavaScript's Methods that use Regular
Expression
Regexe are meant for searching and manipulating text string. Hence,
the String and RegExe objects have many methods to operate on regexe and
string.
String Object
• aStr.match(regexe): Match this string with the given regexe. Returns the
matched substring or null if there is no match.
• aStr.search(regexe): Search this string for the given regexe pattern.
Returns the beginning position of the matched substring or -1 if there
is no match.
• aStr.replace(regexe,+replacement): Search the string for the
given regexe pattern. If found, replaces the matched substring it with
the replacement string.
• aStr.split(regexe): Split this string using the delimiter pattern defined
in regexe. Returns an array of strings containing the splitting parts.
RegExe Object
• aRegexe.test(aStr): Tests this regexe against the given string. Returns
boolean true or false.
• aRegexe.exec(aStr): Executes a search for a match in a string and returns
the first match (or an array of matched substring with "g" modifier).
• aRegexe.compile(): Compile this regexe to improve the running efficiency.
Example: aStr.match(aRegexe) and aRegexe.test(aStr)
var+msg+=+"Hello+world";+
var+pattern+=+/hell/;++++//+case+sensitive+matching+
document.write(msg.match(pattern)+++"<br+/>");+//+null+(no+match)+
document.write(pattern.test(msg)+++"<br+/>");++//+false+
++++
pattern+=+/hell/i;+++++++//+case+insensitive+matching+
document.write(msg.match(pattern)+++"<br+/>");+//+"Hell"+
document.write(pattern.test(msg)+++"<br+/>");++//+true+
Example: aStr.replace(aRegexe,:replacementStr)
var+msg1+=+"This+is+a+string";+
var+pattern+=+/is/;++++++//+First+match+only+
document.write(msg1.replace(pattern,+"was")+++"<br+/>");+//+Thwas+is+a+string+
var+pattern+=+/is/g;+++++//+All+matches+(global)+
document.write(msg1.replace(pattern,+"was")+++"<br+/>");+//+Thwas+was+a+string+
Example: aStr.search(aRegexe)
[TODO]
Example: aStr.split(aRegexe)
[TODO]
14. Miscellaneous
14.1 Task Scheduling via Timeout
Two methods, setTimeout(codes,+milliseconds) and clearTimeout(timeoutName) are
provided to schedule a piece of codes to be executed after a specified
milliseconds.
var+task+=+setTimeout("alert('Hello')",+10000);+
The variable task permits you to cancel the scheduled time event before
timeout if desires:
cancelTimeout(task);+
Operator Description
<< Left bit-shift (padded with 0s)
>> Signed right bit-shift (padded sign-bit)
>>> Unsigned right bit-shift (padded with 0s)
& Bitwise AND
| Bitwise OR
~ Bitwise NOT (1's compliment)
^ Bitwise XOR
Similarly, the following bitwise operation cum assignment operators are
provided: <<=, >>=, >>>=, &=, |=, ^=.
14.3 Operator Precedence
Operator Name Operat
Parentheses, Array index, Dot ()+[]+.+
Negation, Increment/Decrement !+~+_++++__+
Multiply, Divide, Modulus *+/+%+
Addition, Subtraction ++_+
Bitwise Shift <<+>>+>>>+
Relational <+<=+>+>=+
Equality ==+!=+
Bitwise AND &+
Bitwise XOR ^+
Bitwise OR |+
Logical AND &&+
Logical OR ||+
Ternary (Shorthand if-else) ?+:+
Assignment =++=+_=+*=+/=+%=+
Comma (separate parameters) ,+
14.4 Try-catch and Exception Handling
[TODO]
14.5 Execute JavaScript Statement from Browser's
Address Bar
You can issue You can execute JavaScript from Firefox's navigator toolbar
or Internet Explorer's address bar, via pseudo-
protocol javascript:statement. For example,
javascript:alert('Hello');+
javascript:alert(document.title);alert('Hello,+again')+
javascript:document.title+
The statement can access variables and objects on the current document.
The JavaScript statement used in a javascript: URL should not return any
value. For example, alert() does not return a value (or
returns undefined).+If it returns an explicit value, the browser loads a
new page and places the returned value in the body of the page.
You can use the void operator to stay in the same page. void evaluates its
expression, and returns undefined. For example,
javascript:void(x=5)+
javascript:void(document.body.style.background='#FFF');+
For example,
[TODO]
PHP provides functions json_encode() and ison_decode() to convert JSON to
array.