Sie sind auf Seite 1von 61

JavaScript

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:

• 1.8 (2008), Latest 1.8.5: ECMA-262 5th edition compliance (Firefox 4)


1.1 JavaScript vs. Java
Java is a full-fledged general-purpose programming language created by
James Gosling at Sun Microsystems (now part of Oracle), released in Aug
1995. JavaScript is created by Brendan Eich at Netscape in 1995.
Originally called LiveScript, it is a small and lightweight special-
purpose language for writing client-side program running inside the web
browser to create active user-interface and generate dynamic web pages.
Java also supports client-side programming via the so-called Java applets.
JavaScript is not a general-purpose nor a stand-alone programming language
(it has to be run inside the browser). It was originally called LiveScript
and was renamed to JavaScript in an ill-fated marketing decision to try to
capitalize on the popularity of Java language, when Netscape released it
Navigator 2 in 1996 (Navigator 2 also runs the Java applets). Java and
JavaScript are totally different languages for different programming
purposes. However, in the early days, some efforts were made to adopt Java
syntaxes and conventions into JavaScript, such that JavaScript seems to be
a subset of Java. In reality, they have very little in common. But, if you
know Java, you should find JavaScript easier to learn because of these
common syntaxes.
1.2 What JavaScript Cannot Do
Remember that JavaScript is a client-side program that you downloaded from
a server, and run inside the browser of your (client) machine. What to
stop someone from writing a JavaScript that wipes out your hard disk, or
triggers a denial-of-service attack to another server? As a result, for
security purpose,
1. It cannot read file from the client's machine.
2. It can only connect to the server that it come from. It can read file
from the server that it come from. It cannot write file into the
server machine.
3. It cannot connect to another server.
4. It cannot close a window that it does not open.

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.

3. Getting Started by Examples


Let us begin by looking at some simple JavaScripts.
3.1 Example 1: Functions alert() and document.write()

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>+

(You can now omit type="text/javascript". Older versions of JavaScripts


use Language="JavaScript". Both type and language are not needed in HTML
5.)
4. You could place the script in either the HEAD section (called header
script) or BODY section (called body script) of an HTML document. You
are free to embed as many scripts into a single document as you like,
using multiple <script>...</script> tags. Lines 4-6 and Line 10-14 are
two pieces of JavaScripts, placed in the HEAD and BODY sections,
respectively.
5. JavaScript statements are terminated by a semi-colon ';'.
6. The alert(string) function (Line 5) pops out a dialog box displaying
the string and a OK button. Strings are enclosed by a pair of double
quotes or single quotes.
7. The current web page is represented by the so-called document object
in the JavaScript. The document.lastModified (Line 13) property stores
the last modified date of the current document.
The document.write(string) function (Line 11 to 13) can be used to write
the specified string to the current document, as part of the current
HTML document.
8. The "+" operator (Line 13) concatenates
Text pieces of the strings,
link things together
similar to Java language.
9. As the result of the document.write(), the BODY section of this
document contains:
10. <h1>My+First+JavaScript+says</h1>+

<h2><em>Hello+ world,+ again!</em></h2><p>This+ document+ was+ last+ modified+ on+


mm/dd/yyyy+hh:mm:ss.</p>+

11. alert() and document.write() are some of the commonly-used built-in


functions provided in JavaScript.
TRY: Print the document's title and the URL location. (Hints:
use document.title and document.location properties.)
Control-Refresh (Control-F5): If you modify the codes and reload the
web page, the new codes may not get executed because the
browser caches the previously loaded version. You could use Control-F5
(Control-Refresh) to ask the browser to discard the cached page, and fetch
a new page.
3.2 Example 2: Variable, if-else and
Functions prompt() , confirm()
This script prompts the user for his/her name, confirms the name, and
prints a greeting message.
There are three kinds of pop-up dialog boxes in JavaScript, to interact
with the users:
1. The alert(string) function puts the string on a pop-up box with a OK
button. User needs to click the OK button to continue.
2. The prompt(string,+defaultString) function puts the string on a pop-up
box with OK and Cancel buttons. It returns the input entered by the
user as a string; or a special value called null if the user hits the
Cancel button.
3. The confirm(string) function puts the string on a pop-up box with with
OK and Cancel buttons. It returns true if user hits the OK button;
or false otherwise.
" JSEx2.html "
1+
<html>+
2+
<head>+
3+
++<title>JavaScript+Example+2:+Variables+and+function+prompt()</title>+
4+
++<script:type="text/javascript">:
5+
::::var:username;:
6+
::::username:=:prompt("Enter:your:name::",:"");:
7+
::::if:(confirm("Your:name:is:":+:username)):{:
8+
:::::::document.write("<p>Hello,:":+:username:+:"!</p>");:
9+
::::}:else:{:
10+
:::::::document.write("<p>Hello,:world!</p>");:
11+
::::}:
12+
::</script>+
13+
</head>+
14+
<body>+
15+
++<p>Welcome+to+JavaScript!</p>+
16+
</body>+
17+
</html>+
Dissecting the Program
1. Line 5 declares a variable called username, via the keyword var. A
variable is a named storage location that holds a value. Once the
variable is declared, you can assign (and re-assign) a value to that
variable, via the assignment operator '='(Line 6).
2. Line 6 invokes the prompt(string,+defaultString) function to pop out a
dialog box, and reads in the string entered by the user. The string
read is assigned to the variable username. The function prompt() is
similar to the alert(), but it accepts a user's input. You can also
assign a default value, in this example, an empty string.
3. In Line 7, the confirm(string) function puts up the message and returns
either true or false, depending on whether the user hits the OK or
Cancel button.
4. If the result is true, Line 8 prints "Hello, username!". Otherwise,
Line 10 prints "Hello, world!".
TRY: Instead of printing the greeting message using document.write(), do it
via an alert().
3.3 Example 3: Date Object and Conditional Statement
The following script creates a Date object and prints the current time.
" JSEx3.html "
1+
<html>+
2+
<head>+
3+
++<title>JavaScript+Example+3:+Date+object+and+Conditional+Statement</title>+
4+
++<script:type="text/javascript">:
5+
::::var:now::=:new:Date();++++++++//+current+date/time+
6+
++++var:hrs::=:now.getHours();++++//+0+to+23+
7+
++++var:mins:=:now.getMinutes();:
8+
::::var:secs:=:now.getSeconds();:
9+
::::document.writeln("<p>It:is:":+:now:+:"</p>");:
10+
::::document.writeln("<p>Hour:is:":+:hrs:+:"</p>");:
11+
::::document.writeln("<p>Minute:is:":+:mins:+:"</p>");:
12+
::::document.writeln("<p>Second:is:":+:secs:+:"</p>");:
13+
::::if:(hrs:<:12):{:
14+
::::::document.writeln("<h2>Good:Morning!</h2>");:
15+
::::}:else:{:
16+
::::::document.writeln("<h2>Good:Afternoon!</h2>");:
17+
::::}:
18+
::</script>+
19+
</head>+
20+
<body></body>+
21+
</html>+
Dissecting the Program
• Line 5 declares a variable called now. It also creates a Date object
(via the new operator), which contains the current date-time stamp, and
assign it to now.
• "//" begins an end-of-line comment (Lines 5 and 6). Comments are
ignored by the JavaScript engine but important in explaining your
codes to others (and to yourself three days later).
• Line 6 declares a variable called hrs. It also invokes the
function getHours() on object now, in the form of now.getHours(), to
retrieve the hour part of object now, and assign it to variable hrs.
Lines 7 and 8, similarly, handle the minutes and seconds.
• Line 9 to 12 use document.writeln() to write to the current
document. writeln() (write-line) writes a newline (\n) after the given
string. Take note that browser ignores extra white space (newlines,
blanks, tabs) in an HTML document; you need to write a <p>...</p> or <br+
/> tag to ask the browser to display a line break.
• Lines 13-17 contains a conditional if-then-else statement. Depending
on the value of hrs, one of the messages will be displayed.
TRY:
1. Modify the above script to print the current date, month, year and
day of the week. (Hints: Use
functions getDate(), getMonth(), getFullYear() and getDay() of
a Date object. getDate() returns 1-31. getMonth() returns 0 to 11 for
January to December. getFullYear() returns a 4-digit
year. getDay() returns 0 to 6 for Sunday to Saturday).
2. Use a conditional statement to print the day of the week in word
(i.e., 0 for Sunday, 1 for Monday and etc.). (Hints: Use the if_
elseif_elseif...else construct as follow.)
3. if+(+condition31+)+{+
4. +++statements_1+;+
5. }+else+if+(+condition32+)+{+
6. +++statements_2+;+
7. }+else+if+(+condition33+)+{+
8. +++statements_3+;+
9. .....+
10. }+else+{+
11. +++statements_n+;+

}+
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+;+

}+

There are four parts in a for-loop. Three of


them, initialization, test and post-processing, are enclosed in
brackets () and separated by 2 semi-colons. The bodycontains the
repetitive task to be performed. The initialization statement is first
executed. The test is then evaluated. If the test returns true,
the body is executed; followed by the post-processing statement.
The test is evaluated again and the process repeats until
the test returns false. When the test is false, the for-loop completes
and program execution continues to the next statement after the for-
loop. The following flow chart illustrates the for-loop process:
In this example, the variable number is initialized to 1. If number is
less than or equal to 100, the body of the loop executes, followed by
the post-processing statement, which increment the value of number by
1. The loop repeats until the value of number is NOT less than or equal
to 100 (i.e., more than 100).
TRY:
1. Modify the above script to prompt the user for the multiplier as well
as the number of multiples to be printed (in two prompt() statements).
2. Modify the above script to print only multiples that are odd number.
(Hint: The modulo operator "%" can be used to compute the remainder,
e.g., x+%+2 computes the remainder of x divides by 2, which results in
either 0 or 1.)
3.5 Example 5: User-defined Function and onclick
Besides the JavaScript built-in functions such as alert(), prompt(), write(),
and writeln(), you can define your own functions. A function has a name and
a body consisting of a set of JavaScipt statements that collectively
performs a certain task. It may take zero or more argument(s) from the
caller and return zero or one value back to the caller.
" JSEx5.html "
1+
<html>+
2+
<head>+
3+
++<title>JavaScript+Example+5:+User_defined+function+and+Event+onclick</title>+
4+
++<script:type="text/javascript">:
5+
::::function:openNewWindow():{:
6+
::::::open("JSEx1.html");:
7+
::::}:
8+
::</script>:
9+
</head>+
10+
<body>+
11+
++<h2>Example+on+event+and+user_defined+function</h2>+
12+
++<input+type="button"+value="Click+me+to+open+a+new+window"+
13+
+++++++++onclick="openNewWindow()">+
14+
</body>+
15+
</html>+
Dissecting the Program
• Lines 5-7 define a function called openNewWindow(), via the
keyword function. The function invokes the built-in function open(url),
which opens a new browser window (or tab) and loads the page
"JSEx1.html".
• Lines 12-13 create an HTML button. Clicking the button triggers
the onclick event handler, i.e., openNewWindow() defined earlier.
TRY: Include another button, which opens "JSEx2.html".
3.6 Example 6: Event Handlers: onload, onunload,
onmouseover, onmouseout
JavaScript can be used to handle many types of events, in response to a
user's action or browser's action. For example,

• onload: fires after browser loaded the page.


• onunload: fires before the page is removed, e.g. another page is to be
loaded, refreshing this page, or the window is closing.
• onmouseover and onmouseout: fires when the user points the mouse pointer
at/away from the HTML element.
" JSEx6.html "
1+
<html>+
2+
<head>+
3+
++<title>JavaScript+Example+6:+Events+onload+and+onunload</title>+
4+
++<script:type="text/javascript">:
5+
::::var:msgLoad:=:"Hello!";:
6+
::::var:msgUnload:=:"Bye!";:
7+
::</script>+
8+
</head>+
9+
<body+onload="alert(msgLoad)":onunload="alert(msgUnload)">+
10+
++<p>"Hello"+alert+Box+appears+<em>after</em>+the+page+is+loaded.</p>+
11+
++<p+onmouseover="this.style.color='red'"+
12+
+++++onmouseout="this.style.color=''">Point+your+mouse+pointer+here!!!</p>+
13+
++<p>Try+closing+the+window+or+refreshing+the+page+to+activate+the+"Bye"+alert+box.</p>+
14+
</body>+
15+
</html>+
Dissecting the Program
• Line 5 and 6 define two variables, msgLoad and msgUnload, which hold the
strings to be displayed in the onload and onunload event handlers.
• In the <body> start-tag (Line 9), we define the onload and onunload event
handlers for the load and unload events. They invoke alert() with the
message defined earlier.
• Line 11 and 12 defines the event handlers onmouseover and onmouseout for
the HTML element <p>. The text's color will be changed to red when the
user points the mouse pointer at the element (by setting the CSS style
property color to red), and revert back to its original color when the
mouse pointer is moved away (by resetting the CSS style
property color to an empty string). The special keyword this refer to
this object.
3.7 Example 6a: Separating HTML, CSS and JavaScript
The previous example works fine. You will find many such example in
textbooks, especially the older textbooks. However, it has a big problem.
All the HTML contents, CSS presentation styles and JavaScript programming
codes are placed in a single file. For a small toy program, the problem is
not serious. But when your program grows and if the HTML, CSS and
JavaScript are written by different people, you will have a real challenge
in maintaining the program.

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.

a. <link: rel="stylesheet": href="JSEx6a.css">


The CSS style sheet is kept in an external file, referenced via
the above <link> tag.
b. <script: type="text/javascript": src="JSEx6a.js"></script>
Also, the JavaScript programming code is kept in an external
file, referenced via the above <script> tag.
c. <p: id="magic">Point: your: mouse: pointer: here!!!</p>
We provide an unique id to this <p> tag. This id will be used in
the JavaScript to select this tag.
3. The CSS file contains only one style definition:
.red: {: color:red;: }
This define a class-selector called red to display the element
with class="red" in color red.
4. In the JavaScript:

. window.onload: =: function(): {: ...: }


We attach a so-called inline function as the onload event
handler. This function will be invoked after the page is fully
loaded.
a. document.getElementById("magic").onmouseover:=:function():{:this.className:
=: "red";: }
We use document.getElementById("magic") function to select the <p+
id="magic"> element. We then attach an inline function as
the onmouseover event handler for this <p> element. When the user
moves the mouse over this element, this function changes
the class attribute to "red". In response, the CSS turns the <p>
element to color red.
b. document.getElementById("magic").onmouseout: =: function(): {: this.className:
=: "";: }
Similarly, when the user moves the mouse out of the <p+
id="magic"> element, the event handler changes the class attribute
to "". In response, CSS changes the color to its default.
c. alert("Hello!")
This puts up an alert dialog box.
d. window.onunload: =: function(): {: alert("Bye!");: }
Similarly, we attach an inline function as the onunload event
handler, which pops up an alert dialog box, before the page is
unloaded.
3.8 Example 7: Modifying the Contents of HTML
Elements and External Script
You can select HTML element(s) within the current page via these
functions:
1. document.getElementById(anId): returns the HTML element with id="anId",
or null if the id does not exist. The id attribute should be unique
within an HTML document.
2. document.getElementsByName(aName): returns an array of HTML elements
with name="aName". Take notes of the plural elements. More than one
elements can have the same name attribute.
3. document.getElementsByTagName(aTagName): returns an array of HTML elements
with the given HTML tag name.
To modify the content of an HTML element, you can assign a new value to
the innerHTML property of that element. (The property innerHTML is really
useful and is supported in most of the browsers. It is, however, not
included in the W3C DOM specification?!)
" JSEx7.html "
1+
<html>+
2+
<head>+
3+
++<title>JavaScript+Example+7:+Modifying+the+Content+of+HTML+Elements</title>+
4+
++<script+type="text/javascript"+src="JSEx7.js"+></script>+
5+
</head>+
6+
<body>+
7+
++<h1+id="heading1">Heading+1</h1>+
8+
++<h2>Heading+2</h2>+
9+
++<h2>Heading+2</h2>+
10+
++<p+name="paragraph">Paragraph+1</p>+
11+
++<p+name="paragraph">Paragraph+2</p>+
12+
++<p+name="paragraph">Paragraph+3</p>+
13+
++<input+type="button"+id="btn1"+value="Change+Heading+1"+/>+
14+
++<input+type="button"+id="btn2"+value="Change+Heading+2"+/>+
15+
++<input+type="button"+id="btn3"+value="Change+Paragraph"+/>+
16+
</body>+
17+
</html>+
" JSEx7.js "
1+
window.onload+=+init;+
2+
++
3+
function+init()+{+
4+
++document.getElementById("btn1").onclick+=+changeHeading1;+
5+
++document.getElementById("btn2").onclick+=+changeHeading2;+
6+
++document.getElementById("btn3").onclick+=+changeParagraph;+
7+
}+
8+
++
9+
function+changeHeading1()+{+
10+
++document.getElementById("heading1").innerHTML+=+"Hello";+
11+
}+
12+
++
13+
function+changeHeading2()+{+
14+
++var+elms+=+document.getElementsByTagName("h2");+
15+
++for+(var+i+=+0;+i+<+elms.length;+i++)+{+
16+
++++elms[i].innerHTML+=+"Hello+again!";+
17+
++}+
18+
}+
19+
++
20+
function+changeParagraph()+{+
21+
++var+elms+=+document.getElementsByName("paragraph");+
22+
++for+(var+i+=+0;+i+<+elms.length;+i++)+{+
23+
++++elms[i].innerHTML+=+"Hello+again+and+again!";+
24+
++}+
25+
}+
Dissecting the Program
1. In this example, instead of placing the scripts inside the HTML
document, we place the JavaScript in a separate file called "JSEx7.js"
and referenced this file in the HTML page via <script+ src="JSEx7.js">.
The external script file shall have the file extension of ".js".
External Script is recommended as it separates the HTML content and
the programming script (called unobstructive scripting), for ease of
maintenance (just like HTML content and CSS presentation should be
separated). You can also use the same script in many HTML pages.
2. This HTML document contains a <h1> element with an
unique id="heading1" (Line 7), two <h2> elements (Line 8-9),
three <p> elements with name="paragraph" (Line 10-12), and three <input+
type="button"> with unique id (Line 13-15).
3. In the user-defined function changeHeading1(), we
use document.getElementById("heading1") to select the <h1> element, and
then modify its innerHTML property.
4. In changeHeading2() function, we use document.getElementsByTagName("h2") to
select all the <h2> elements in an array elms. We then use a for-loop
to iterate thru all the elements in the array.
The elms.length property keeps the length of the array.
5. In changeParagraph() function, we
use document.getElementsByName("paragraph") to select all
the <p> elements.
6. The page contains three buttons to trigger the functions defined
(Line 13-15).
7. The script also contain a function init(), which is assigned as
the onload handler via window.onload=init. That is, init() will be
triggered after the page is loaded. The init() function
assigns onclick event handlers to the buttons, selected
via document.getElementById().
8. Take note that there is no script code in the HTML page, except
reference to the external script file.
TRY: [TODO]
3.9 Example 8: Intercepting an Hyperlink
This example uses a script to intercept an hyperlink to put up a warning
message, but proceeding to the link.
" JSEx8.html "
1+
<html>+
2+
<head>+
3+
++<title>JavaScript+Example+8:+Intercept+an+Hyperlink</title>+
4+
++<script+type="text/javascript"+src="JSEx8.js"+></script>+
5+
</head>+
6+
<body>+
7+
++<a+href="JSEx1.html"+id="linkEx">JavaScript+Example+1</a>+
8+
</body>+
9+
</html>+
" JSEx8.js "
1+
window.onload+=+init;+
2+
++
3+
function+init()+{+
4+
++document.getElementById("linkEx").onclick+=+showWarning;+
5+
}+
6+
++
7+
function+showWarning()+{+
8+
++return+confirm("Warning!+Proceed+with+care!");+
9+
}+
Dissecting the Program
1. The HTML page has an hyperlink <a> with an unique id.
2. The init() function assigns an onclick handler to the hyperlink,
selected via document.getElementById()..
3. When the hyperlink is clicked,
the onclick handler showWarning() triggered. If confirm() returns true,
the new page will be loaded; otherwise, the current page remains.
TRY: [TODO]
3.10 More Advanced JavaScript Examples
More "Advanced JavaScript Examples".
4. Writing and Debugging JavaScripts
A good graphic debugger is a MUST for programming in any language.
Programming in JavaScript, in particular, requires a graphic debugger. It
is because JavaScripts are interpreted and does not need to be compiled.
Hence, there is no compiler to show you the syntax errors. A simple and
trivial syntax error (e.g., missing bracket, mis-spelling) will render the
entire script not workable. Worst still, most of the times, you cannot see
any error message when the script does not work (unless you enable the
error console). Can you debug without any error message or clue?
Without a graphic debugging, the only mean to debug JavaScript is to
insert alert() at strategic locations to print out selected data.

In addition, a good IDE with content-assist (auto-complete) feature, which


provide a list of possible options, would be a great help.

After modifying a JavaScript, I recommend that you use Ctrl-F5 to refresh


the page, which shall load a fresh copy instead of loading from the cache.
You might need to clear the browser's cache or re-start the browser, if
you modification does not take effect.
4.1 Firebug add-on for Firefox - ESSENTIAL
Simply GREAT and MUST HAVE for debugging HTML/CSS and JavaScript!!! You
can install firebug from http://getfirebug.com/. It provides these
features:
1. Console: View the JavaScipt error messages. Start the firebug and
switch to the "Console" panel.
2. Script: View and debug JavaScipt. Start the firebug. Switch to the
"Script" panel. "Enable" or "Reload" if necessary. You can set a
breakpoint by clicking on the statement number, single step thru the
JavaScript statements, watch the expression, and etc. Read
"JavaScript Debugger and Profiler".
3. DOM: View the HTML DOM of the current document.
4. HTML and CSS.
How to debug JavaScript in Firebug
1. Launch Firebug ⇒ Choose the Script panel ⇒ Reload the page.
2. Set breakpoints at selected JavaScript statements, by clicking on the
right margin (to the left of line number). A red circle shows up
denoting a breakpoint. Take note that you can only set breakpoint on
statements with a green-bold line number. If your JavaScript
statements do not have a green-bold line number, there are syntax
errors on these statements. You need to correct the syntax errors and
reload the page.
3. Trigger the script (via clicking button/link, or reloading the page).
The execution stops at the first breakpoint. You can then step-over
the statement (or step-into function), and inspect the variables by
positioning the mouse pointer on the variable; or add the variable to
"watch".
4. You can resume the execution (via the continue button).

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]

5. JavaScript & HTML


As seen from the previous examples, JavaScripts are embedded inside an
HTML document, and executed by the browser. There are two occasions on
which browser executes JavaScript instructions:

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).

There are, therefore, two places to put your JavaScript:

1. between <script> and </script> container tags; and


2. inside the HTML tags as the event handlers (such
as onclick, onmouseover, onload), e.g., onclick="JavaScriptStatements".
5.1 The <script>...</script> Tags
The <script>...</script> tags contains the JavaScript programming
statements. The attribute type="text/javascript" identifies the scripting
language (Older scripts may use Language="JavaScript".
Both type and language are not needed in HTML 5). For example,

<script+type="text/javascript">+
...+Your+JavaScript+statements+here+...+
</script>+

It is a old practice (old and legacy practice?!) to enclose the JavaScript


statements by an HTML comments, so that browsers that do not support
JavaScript will treat them as comments and will not try to parse and
display them. This is really not needed today, as all browsers support
JavaScript. For example,

<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?!

The original method of scripting is to place the JavaScript in the HEAD


section of the HTML document. But the now-preferred method separate the
HTML contents, CSS presentation styles, and JavaScript programming codes
in three separate files. You can share the script among many HTML pages,
and it is much more easier to maintain.
5.4 The <noscript>...</noscript> Tags
The <noscript>...</noscript> tags provide an alternate message if scripting
is disabled or not supported.
6. JavaScript Basic Syntax
6.1 Comment
Comments are ignored by the JavaScript runtime but greatly useful in
explaining your codes to others (and also to yourself three days later).
You should use comments liberally to explain or document your codes.

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;+

Unfortunately, IE does not support this keyword?! So don't use.


6.5 " Number " Type, Literals & Operations
A variable of type Number holds a number, either an integer (e.g., 5566),
or a floating-point number (e.g., 3.1416). Integer literals can be
expressed in decimal (begins with a digit 1 to 9), octal (begins with a
digit 0, e.g., 0123) or hexadecimal (begins with 0x, e.g., 0xA1B2).
Floating-point literals can be expressed in scientific notation
(e.g., 1.23e4, 4.56e_7). JavaScript also provides some
special Number literals such as infinity (e.g., 1/0), _infinity (e.g., _
1/0), NaN (Not-A-Number, e.g., 0/0, or converting the string 'Hello' to a
number).
Arithmetic Operations
Arithmetic operations, as tabulated below, can be applied to numbers. The
following results are obtained assuming that x=5, y=2 before the operation.
Operator Description Example ( x=5 , y=2 )
+ Addition z = x + y;
- Subtraction (or z = x - y;
Unary Negation)
* Multiplication z = x * y;
/ Division z = x / y;
% Modulus (Division z = x % y;
Remainder)
++ Unary Pre- or y = x++; z = ++x;
Post-Increment Same as: y = x; x = x+1; x = x+1; z = x;
-- Unary Pre- or y = --x; z = x--;
Post-Decrement Same as: x = x-1; y = x; z = x; x = x-1;
In JavaScript, arithmetic operations are always performed in double-
precision floating-point. That is, 1/2 gives 0.5 (instead of 0 in
Java/C/C++). You may use the built-in function parseInt() to truncate a
floating-point value to an integer,
e.g.,parseInt(55.66) and parseInt("55.66") gives 55. You may also use the
built-in mathematical functions such
as Math.round(), Math.floor(), Math.ceil() for converting a floating-point
number to an integer.
Arithmetic cum Assignment Operators

These are short-hand operators to combine two operations.

Operator Description Example


+= Addition cum x += y;
Assignment
-= Subtraction cum x -= y;
Assignment
*= Multiplication cum x *= y;
Assignment
/= Division cum x /= y;
Assignment
%= Modulus cum x %= y;
Assignment
6.6 " String " Type, Literals & Operations
A variable of the type String hold a sequence of text characters. A string
literal is texts delineated by single quotes or double quotes
(e.g., "Hello", 'world', "5566", '3.1416'). You can use an escape sequence to
represent special characters (such as \n for new-line, \t for tab,
and \uhhhh for Unicode character); and to resolve conflict
(e.g., \", \', \\).
JavaScript is dynamically-type, and performs type conversion
automatically. When a String value is used in arithmetic operations (such
as subtraction or multiplication), JavaScript runtime automatically
converts the String to a Number if it represents a valid Number, or a
special Number called NaN (Not-A-Number) otherwise. For example,
//+ In+ arithmetic+ operation+ (except+ addition),+ strings+ are+ converted+ to+ number+ (or+
NaN)+
var+magic;+
magic+=+"55"+_+"66";+++//+gives+number+_11+(subtraction)+
magic+=+"55"+*+2;++++++//+gives+number+110+(multiplication)+
magic+=+"Hello"+_+1;+++//+gives+number+NaN+(subtraction+failed)+
Operator '+'
If both the operands to a '+' operator are Numbers, it performs the
usual addition. However, if one of the operand is a String,
the '+' operator is overloaded to perform string concatenation. The other
operand will be converted to a String if necessary. For example,
//+'+'+operator+is+overloaded+to+perform+string+concatenation+if+one+of+the+operands+
is+a+string+
alert(11+++22);+++++++//+gives+Number+33+(usual+addition)+
alert("11"+++"22");+++//+gives+string+1122+(concatenation)+
alert("11"+++22);+++++//+gives+string+1122+(concatenation)+
alert("Hello"+++22);++//+gives+string+Hello22+(concatenation)+
Built-in Functions parseInt() and parseFloat()
To convert a numeric String to a Number, you could use the built-in
function parseInt() or parseFloat(), which returns a Number if conversion is
successful, or NaN otherwise. For example,
var+magic+=+"11";++//+String+
alert(magic+++22);++//+String+"1122"+
alert(parseInt(magic)+++22);+++//+Number+33+
alert(parseInt(magic)+++"22");+//+String+"1122"+
alert(parseInt(magic)+++parseFloat("22.33"));++//+Number+33.33+
alert(parseInt("abc"));+++//+NaN+
6.7 " Boolean " Type, Literals & Operations
A variable of the type Boolean holds a value of
either true of false. true and false are keywords in JavaScript.
As mentioned, JavaScript performs automatic type conversion if necessary.
During the type conversion, the following values are converted to false:
number 0, empty string ("", ''), NaN, null, and undefined. All the other
values are converted totrue.
Comparison Operators
The following relational operators, which produce a boolean result, are
defined in JavaScript. The results are obtained assuming num=8, str='8'.
Operator Description Example
== Equal To num == 8
str == '8'
num == str
8 == '8'
!= Not Equal To
=== Strictly Equal To num === 8
(in Type and Value) str === '8'
num === str
8 === '8'
!== Strictly Not Equal To
> Greater Than
>= Greater Than or Equal To
< Less Than
<= Less Than or Equal To
=== (!==) vs. == (!=)

Comparison can be applied to two numbers, a number and a string, or two


strings:
• When a number is compared with a string, the string is converted to a
number (or NaN if it does not contain a valid number). Hence, (8+ ==+
"8") returns true. A strict equal-to operator (===) is introduced in
JavaScript, which compares both the value and the type. Hence, (8+ ===+
"8") returns false.
• When two strings are compared, the alphabetic order (ASCII code table)
is used. Hence, string "8" is alphabetically greater than string "10".
• ===, !==, ==, != can be applied to boolean too, e.g., (""+ ==+
false) gives true (because empty string is converted to false); but (""+
===+false) gives true.
• It is RECOMMENED to always use === (or !==), instead of == (or !=).

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

The following boolean (or logical) operators are provided in JavaScript:

Operator Description Example


&& Logical AND
|| Logical OR
! Logical NOT
Evaluation of logical operations are always short-circuited. That is, the
operation is terminated as soon as the result is certain, e.g., (false+ &&+
...) is short-circuited to give false, (true+||+...) gives true, the ... will
not be evaluated.
6.8 Explicit Type Conversion
The JavaScript runtime performs type conversion automatically. However, at
times, you may need to convert from one type to another explicitly.
Convert a Number to a String : Simply concatenate the number with an
empty-string, e.g., ""+++5 gives "5".
Convert a String to a Number : Use built-in
functions parseInt(string) and parseFloat(string) to convert a string which
contains a valid number. For
example, parseInt("55") gives 55, parseInt(55.66) gives 55,parseInt("55.66") giv
es 55, parseFloat("55.66") gives 55.66, but parseInt("Hello") gives NaN.
Convert a float to an integer : Use parseInt(),
e.g., parseInt(55.66) gives 55, or built-in mathematical functions such
as Math.round(), Math.ceil() or Math.floor().
6.9 Scope of a Variable
When a variable is declared inside a function or block, it is
a local variable and its scope is within the function or block. When a
variable is declared outside functions, it is a global variable and is
available to all the codes in the current document.
6.10 Flow Control
JavaScript provides these flow control construct. The syntax is the same
as Java/C/C++.

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;+
}+

The following loop-control statements are provided (same syntax as


Java/C/C++):
• break: exit the innermost loop.
• continue: abort the current iteration, and continue to the next
iteration.
• label: provide an identifier for a statement, which can be used
by break and continue.
6.12 Functions
Functions are useful:
• when you have to use the same codes several times.
• as the JavaScript event handler.
• make your program easier to read and understood.

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.

The syntax for user-defined function is:

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+

alert('The+ sum+ is+ '+ ++ (parseInt(number1)+ ++ parseInt(number2)));+ //+ Add+ two+


numbers+

• confirm(string): Pop-up a box and ask user to confirm some information.


The user will have to click on "OK" or "Cancel" to
proceed. confirm() which returns a boolean value. For example,
• var+isFriday+=+confirm("Is+it+Friday?");++//+Returns+a+boolean+
• if+(isFriday)+{+
• +++alert("Thank+God,+it's+Friday!");+
• }+else+{+
• +++alert('Not+a+Friday');+

}+

• document.write(string) and document.writeln(string): Write the specified


string to the current document. writeln() (write-line) writes a newline
after the string, while write() does not. Take note that browser
ignores extra white spaces (blanks, tabs, newlines) in an HTML
document, and treat multiple white spaces as a single blank character.
You need to write a <br+ /> or <p>...</p> tag to ask the browser to
display a line break.
6.14 Other Top-level Built-in Functions
JavaScript also pre-defines the following top-level global functions.
• parseInt(string), parseFloat(string): parses the given string and returns
the numeric value or NaN (Not-A-Number). parseInt(str,+radix) accepts an
optional radix (or base). For example,
• parseInt("88");++++++//+gives+number+88+
• parseInt("88.99");+++//+gives+number+88+
• parseInt("Hello");+++//+gives+NaN+(Not_A_Number)+
• parseFloat("88.99");+//+gives+number+88.99+

parseFloat('Hi');++++//+gives+NaN+

• isFinite(number): returns true if number is not NaN, Infinity or _Infinity.


• isNaN(number): returns true if number is NaN. Useful for checking the
output of parseInt() and parseFloat().
• eval(codes): evaluate the given JavaScript codes, which could be an
expression or a sequence of statements.
• encodeURI(), decodeURI(), encodeURIComponent(), decodeURIComponent(): encode
or decode name-value pairs for the HTTP request, by replacing special
characters with %xx.
6.15 An Introduction to Events
JavaScript are often event-driven. That is, a piece of codes (called event
handler) fires in response to a certain user's or browser's action, which
generates an event.

The commonly-used events are:

• click: generated when the user clicks on an HTML element.


• mouseover, mouseout: generated when the user positions the mouse pointer
inside/away from the HTML element.
• load, unload: generated after the browser loaded a document, and before
the next document is loaded, respectively.
The event handler, called oneventname (such as onclick, onmousemove, onload),
is the codes that responses to an event. The event handler is typically
attached to the target HTML tag, e.g.,

<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>+

More about events in the later sections.


6.16 undefined Function Arguments and default
Function Arguments
Javascript lets you call functions omitting some trailing arguments,
filling in the omitted arguments with the value undefined. For example,

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:

• Properties (also called variables, attributes): contains values


associated with the object.
• Methods (also called operations, functions): contains actions that the
object can perform.

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.+

7.4 null vs undefined value


null is a special literal value for object type, denoting no value or not
allocated. undefined is a type, for variables that have not been declared;
or have been declared but no value assigned. undefined is also a value for
variables that have been declared, but no value assigned. For example,
document.writeln("<p>"+++typeof(undefined)+++"</p>");+++//+undefined+
document.writeln("<p>"+++typeof(null)+++"</p>");++++++++//+object+

In boolean expression, both the null and undefined evaluate to false.


8. Built-in JavaScript Objects
JavaScript provides many useful global objects, such as Array, Date, String,
and Number.
I shall discuss some commonly used objects here. For detailed
specification and examples about a built-in object, check "Core JavaScript
References".
8.1 Common Properties and Methods for all
JavaScript objects
Recall that an object is a collection of properties and methods.

The following methods are available to all JavaScript objects:


• anObjectName.toString(): returns a string description about this object.
• anObjectName.valueOf(): converts this object to a primitive value such
as number.
8.2 Array Object
An array can be used to store a list of items under a single name. You can
reference individual item via an index number in the form
of anArrayName[index]. You can conveniently process all the elements in an
array collectively via a loop.
JavaScript does not have an explicit array type. Instead, a built-
in Array object is provided. You can create an Array object in two ways:
1. Invoke the Array constructor with new operator, e.g.,
2. //+(1)+Create+an+Array+object+given+the+length+of+the+array+
3. var+fruits+=+new+Array(3);+
4. fruits[0]++=+"apple";+
5. fruits[1]++=+"orange";+
6. fruits[2]++=+"banana";+
7. document.write(fruits.length);++//+3+
8. ++++
9. //+(2)+Create+an+Array+object+and+initialize+the+array+
10. var+days+=+new+Array("sun",+"mon",+"tue",+"wed",+"thu",+"fri",+"sat");+
11. document.write(days[0]);+++++++//+"sun"+

document.write(days.length);+++//+7+

12. Assign directly to an array literal, in the form of [value1,+value2,+


...]

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.

Array is usually processed collectively using a loop, e.g.,

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.

It has these commonly-used methods:


• join(separator): join the elements of an array together into a single
string, separated by the separator (defaulted to ","). For example,
• var+fruits+=+["apple",+"orange",+"banana"];+++//+Create+an+array+object+
• fruits.join();+++++//+gives+"apple,orange,banana"+

fruits.join("|");++//+gives+"apple|orange|banana"+

• concat(value1,+value2,+...,+valueN): returns a new array composing of this


array and the given arrays or values.
• reverse(): reverses the order of elements in the array, the first
becomes last.
• sort(): sorts the elements in the array.
• push(): adds one or more elements to the end of an array and returns
the last element added.
• pop(): removes and return the last element from an array.
• shift(): removes and returns the first element from an array.
• unshift(): adds one or more elements to the front of an array and
returns the resultant length of the array.
• splice(): adds and/or removes elements from an array.
• slice(): extracts and returns a section of an array (sub-array).
Important: For detailed specification and examples about a built-in
object, check "Core JavaScript References".
Example: [TODO]
8.3 String Object
A string can be created in two ways:
1. directly assigned a string literal in the form of "..." or '...'.
2. invoke the String object constructor via the operator new, i.e., new+
String(content).

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+

The former is called a string literal, while the later constructs


a String object. String object is a wrapper for primitive string, which
provides many useful methods for manipulating strings.

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.

These methods correspond to an HTML tag:


• anchor(aName), link(url): turns the string into HTML anchor tag <a+
name="aName"> or <a+href="url">.
• big(), small(), strike(), blink(), bold(), italics(), fixed(), sub(), sup():
same as the corresponding HTML tag.
8.4 Number Object
Number object is a wrapper object for primitive number, which provides many
properties and methods.
8.5 Boolean Object
Boolean object is a Wrapper object for primitive boolean, which provides
many properties and methods.
8.6 Date Object
Commonly-used constructors:

• 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:

• E, PI: Euler’s constant and PI.


• LN2, LN10, LOG2E, LOG10E: ln(2), ln(10), log2(e), log10(e).
• SQRT2, SORT1_2: square root of 2 and half.

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+

You can define a inline (anonymous) function and assign it to a variable


as follows:

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));+

The syntax for Function constructor is:


functionName+=+new+Function("argument1",+"argument2",+...,+"functionBody");+

9. Defining Your Own Objects


There are two ways to define and create your own objects:

1. define a constructor (called procedural approach)


2. via an object initializer (i.e., assigned a object literal).
9.1 Creating new objects via Constructor and " new "
operator
You can create your own objects by defining a constructor, and invoke the
constructor with the new operator to create a new object.
Keyword " this "
"this" refers to the current
object. this.propertyName and this.methodName() refer the property and method
of this object.
Example
Let us define a constructor for a Circle object, with two
properties radius and dateCreated, and two methods getArea() and toString() in
"Circle.js". We shall then use the "CircleTest.js" and "CircleTest.html" to
test theCircle object defined.
" Circle.js "
1+
//+Define+a+constructor+for+the+Circle+object,+
2+
//++with+properties+radius+and+dateCreated,+
3+
//++and+methods+getArea()+and+toString().+
4+
function+Circle(radius)+{+
5+
++//+Properties+
6+
++this.radius+=+radius+||+1;+++++++++//+Default+is+1+
7+
++this.dateCreated+=+new+Date();+++++//+Assigned+an+object+
8+
++//+Methods+
9+
++this.getArea+=+getArea;++++++++++++//+Assigned+a+function+object+
10+
++this.toString+=+circleDescription;+//+Assigned+a+function+object+
11+
}+
12+
++
13+
//+Define+the+method+getArea().+
14+
function+getArea()+{+
15+
++return+this.radius+*+this.radius+*+Math.PI;+
16+
}+
17+
++
18+
//+Define+the+method+circleDescription().+
19+
function+circleDescription()+{+
20+
++return+"Circle+with+radius="+++this.radius+
21+
++++++++++"+created+on+"+++this.dateCreated;+
22+
}+
" CircleTest.js "
1+
//+Create+two+Circle+objects+
2+
var+circle1+=+new+Circle(1.5);+
3+
var+circle2+=+new+Circle(2.6);+
4+
++
5+
//+Invoke+methods+using+dot+operator.+
6+
document.writeln("<p>"+++circle1+++",+Area="+++circle1.getArea()+++"</p>");+
7+
document.writeln("<p>"+++circle2+++",+Area="+++circle2.getArea()+++"</p>");+
" CircleTest.html "
1+
<html>+
2+
<head>+
3+
++<title>Creating+our+own+objects</title>+
4+
++<script+type="text/javascript"+src="Circle.js"></script>+
5+
++<script+type="text/javascript"+src="CircleTest.js"></script>+
6+
</head>+
7+
<body></body>+
8+
</html>+
Dissenting the Program
1. Properties are declared inside the constructor via this.propertyName,
which can then be initialized.
2. Methods can be declared inside the constructor via this.methodName.
There are a few ways to provide the method's definition:
a. Define an ordinary function, and assign the functionName (without
parentheses, which is a function type) to this.methodName, as in
the above example.
b. Assign this.methodName to an inline function, e.g.

this.getArea+=+function()+{+return+this.radius+*+this.radius+*+Math.PI;+};+

c. Invoke the Function constructor with new operator:

this.getArea+=+new+Function("return+this.radius+*+this.radius+*+Math.PI");+

3. +To invoke a method, use anObjectName.aMethodName(arguments). The


parentheses is necessary even there is no augment.
4. The toString() is a special method, which returns a string description
of this object. toString() will be implicitly invoked if an object is
passed into the write(), writeln(), or '+' operator. In other
words, document.write(circle1)is the same
as document.write(circle1.toString()). All the JavaScript built-in
objects has a toString() method.
9.2 Creating objects via Object Initializer
You can create a new object by directly assign an object
literal (called Object Initializer) to a variable. The syntax is as
follows:
objectName+=+{propertyOrMethod1:value1,+propertyOrMethod2:value2,+...+}+

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.

JavaScript's object is simply a collection of name-value pair (of


properties or methods), similar to a hash or an associative array, as
reflected in the above syntax.

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

Iterate a specified variable over all the properties of an object.

Example [TODO]
Loop with

Establishes the default object for a set of statements.

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);+

"prototype" is a powerful tool. It lets you modify existing object in your


program. You can add extra properties or methods to existing objects at
runtime. Any time you attempt to access a property of that isn't defined
in the constructor, JavaScript will check the prototype to see if it exists
there instead, e.g., circle1.getCircumference() and circle1.color in the above
example.
You can implement inheritance via prototype, by setting aChildObject.prototype+
=+new+parentObject().
9.4 Property constructor

All JavaScript objects has a special property called constructor, which


contains a reference to the function that created the object. For example,

//+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>");+

It is recommended to use object initializer to create an associative


array, as follows:

var+student+=+{'name':'peter',+'id':12345,+'gender':'male'};+
+
for+(key+in+student)+{+
+++document.writeln("<p>"+++key+++"+is+"+++student[key]+++"</p>");+
}+

10. Document Object Model (DOM) API for


JavaScript
Document Object Model (DOM), is a standard API that allows programmers to
access and manipulate the contents of an HTML/XHTML/XML document
dynamically inside their program. It models an HTML/XHTML/XML document as
an object-oriented, tree-like structure, known as a DOM-tree, consisting
of nodes resembling the tags (elements) and contents. DOM also provides an
interface for event handling, allowing you to respond to user's or
browser's action.

DOM API is implemented in many languages such as Java, JavaScript, Perl,


and ActiveX. DOM API specification is maintained by W3C. DOM has various
levels:
• DOM Level 0 (DOM0) (Pre-W3C): obsolete
• DOM Level 1 (DOM1) (W3C Oct 1998): obsolete
• DOM Level 2 (DOM2) (W3C Nov 2000) and DOM Level 2 HTML (HTML DOM2)
(W3C Jan 2003)
• DOM Level 3 (DOM3) (W3C Apr 2004): yet to be fully supported by
browsers.
10.1 Finding and Selecting Elements
In JavaScript, we often use DOM API to select elements within the current
document, so as to access or manipulate their contents. The most commonly-
used functions are:

Function Description
document.getElementById(anId)+ Returns the element with the given unique id.

document.getElementsByName(aName)+ Returns an array of elements with the given name a


Several elements may share the same name attribu
document.getElementsByTagName(aTagName)+ Returns an array of elements with the given tag na

You can use wildcard * in document.getElementsByTagName("*") to select all the


elements, e.g.,

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>+

"innerHTML" is the most convenient way to access and manipulate an


element's content. However, it is not a W3C standard, but it is supported
by most of the browsers.
10.3 DOM Tree & Nodes
W3C recommends that you access and manipulate HTML elements via the DOM
tree and nodes. However, it is really an overkill for writing simple
JavaScripts. I present them here again for completeness.
When a browser loads an HTML page, it builds DOM models a web page in a
hierarchical tree-like structure composing of nodes, resembling its HTML
structure.
An example of an HTML document with the corresponding DOM-tree is given
follow. Take note that the text content of an element is stored in a
separate Text node.

<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.

A DOM-tree comprises the following types of nodes:


1. Document Node: the root node representing the entire HMTL document.
2. Element node: represents an HTML element (or tag). An element node
may have child nodes, which can be either element or text node.
Element node may also have attributes.
3. Text Node: contains the text content of an element.
4. Others: such as comment, attribute.

A DOM node has these properties:


• nodeName: contain the name of the node, which is read-only.
The nodeName for an Element node is the tag-name; nodeName for the
Document node is #document; nodeName for Text nodes is #text.
• nodeValue: contain the value of the node. nodeValue for Text node is the
text contained; nodeValue for Element node is undefined.
• nodeType: an integer indicating the type of the node, e.g., Element
(1), Attribute (2), Text (3), Comment (8), Document (9).
• parentNode: reference to parent node. There is only one parent node in a
tree structure.
• childNodes: array (or node-list) of child nodes.
• firstChild, lastChild: reference to the first and last child node.
• prevSibling, nextSibling: reference to the previous and next sibling in
the same level.
Take note of the difference between singular and plural terms. For
example, parentNode refer to the parent node (each node except root has one
and only one parent node), childNodes holds an array of all the children
nodes.
The root node of the DOM tree is called document. The root node document has
only one child, called document.documentElement, representing the <html> tag,
and it acts as the parent for two child nodes
representing <head> and <body>tags, which in turn will have other child
nodes. You can also use a special property called document.body to access
the <body> tag directly.
For example, you can use the following node property to access the Text
node "Welcome+to+" in the above example:
document.documentElement.lastChild.childNodes[1].firstChild.nodeValue;+//+"Welcome+to+
"+
document.body.lastChild.firstChild.nodeValue;++++++++++++++++++++++++++ //+same+as+
above+
Example
The following JavaScript lists all the nodes in the <body> section, in a
depth-first search manner, via a recursive function.

<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";+

10.7 Manipulating Nodes


A Node object has these functions:
• aNode.hasChildNodes(): returns true if this node has at least one child
node.
• Manipulating child node:
o aParentNode.insertBefore(newChildNode,+existingChildNode): insert a node
before an existing child node.
o aParentNode.replaceChild(newChildNode,+existingChildNode): replace an
existing child node.
o aParentNode.removeChild(childNodeToRemove): remove the specified child
node.
o aParentNode.appendChild(nodeToAppend): append the given node as the last
child.
• aNode.cloneNode():
Creating a New Element ( createElement() ) and Text Node
( createTextNode() ), Appending a Node ( appendChild() )
To create new text node, you can use document.createTextNode(text) to create
a standalone text-node, followed by an anElementNode.appendChid(aTextNode) to
append the text node to an element.
Similarly, you can use document.createElement(tagName) to create a stand-alone
element, followed by an anElementNode.appendChild(elementToAppend) to append
the created element into an existing element.
For example, we shall create a new text node, as a child of a
new <p> element. We shall then append the new <p> element as the last child
of <body>.

<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>+

Inserting a new Node ( insertBefore() )

<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>+

10.8 The document object


The document object is the root node of the DOM-tree. It can be used to
access all the elements in an HTML page.

It contains these properties:


• documentElement, body, title: references the <html>, <body> and <title> tags
respectively.
• lastModified, referrer, cookie, domain: information retrieved from the
HTTP response header.
• form[], applets[], images[], embeds[], links[], anchors[]: Arrays containing
the respective HTML elements (backward compatible with DOM0).
The document object has the following methods:
• write(string), writeln(string): Write the specified string to the current
document. writeln() (write-line) writes a newline after the string,
while write() does not. Take note that browser ignores newlines in an
HTML document, you need to write a <br+ /> or <p>...</p> tag for the
browser to display a line break.
• clear(): Clear the document.
• open(), close(): Open/close the document stream.
• getElementById(), getElementsByName(), getElementsByTagName(): Select HTML
element(s) by id, name, or tag-name, respectively.
11. Event Handling in HTML DOM
JavaScripts are often event-driven. That is, a piece of codes (called
event handler) fire in response to a certain user's or browser's action,
such as clicking a button, enter some texts, or loaded a page.
DOM API provides methods for capturing events so you can perform your own
actions in response to them. It also provides an Event object which
contains information specific to a given event that can be used by your
event handler.
11.1 Attach Event Handler to an HTML tag
You can attach event handler (e.g., onclick, onmouseover) to a specific HTML
tag as the tag's attribute, as follows:
<tagName+eventHandler="JavaScriptNstatement(s)"+otherAttributes+>contents</tagName>+

The event handler can be a single JavaScript statement, a series of


JavaScript statements (separated by semi-colon), or most often, a function
call. For example,

<!__+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>+

You can also define an event handler in script by assigning


a Function object (without parentheses) to an event handler. For example,
<!__+Event+handler+assigned+via+DOM+object+instead+of+inside+HTML+tag+__>+
<p+id="magic">Welcome</p>+
<script+language="javaScript">+
++document.getElementById("magic").onclick:=:myHandler;++//+function+name+without+the+
parentheses+
</script>+
11.2 Built-in Events and Event Handlers
JavaScript supports many types of events, as tabulated below. Certain
events such as click are applicable to all the HTML elements; certain
event such as load and unload are applicable to a selected group of tags.

Event Name Event Handler Descri


click onclick User clicks on the component.
submit onsubmit User clicks the "submit" button.
reset onreset User clicks the "reset" button.
select onselect User selects text in a text box or text area.
keypress onkeypress User holds down a key.
keydown onkeydown User presses/releases a key.
keyup onkeyup
mousedown onmousedown User presses/releases a mouse button.
mouseup onmouseup
mouseover onmouseover User moves the mouse pointer at/away from a link
moueout onmouseout
mousemove onmousemove User moves the mouse pointer
load onload When the page is loaded into the window.
unload onunload When another page is about to be loaded.
blur onblur When a particular form element losses focus.
E.g., after the element is selected, and the use
change onchange Same as onblur, but the elements must be changed.
focus onfocus Same as onblur, but the element gains focus.
drapdrop ondrapdrop User drags and drops something (e.g., a file) on
move onmove User moves/resizes the window
resize onresize
abort onabort Users stops or aborts an image from loading.
error onerror When a JavaScript or image error occurs while lo

[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);+

where eventType is pre-defined event name such as mouseover, mouseout, click,


etc; functionName is the event handler; useCapture is a boolean flag which
specifies at which phase of the event flow (capture or bubble) the event
handler will be called.

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]

12. JavaScript Built-in Browser


Objects: navigator , window , screen , history , location
12.1 The navigator object
The built-in navigator object represents the browser. It contains the
following properties related to the browser:
• platform: Operating system.
• appName, appCodeName, appVersion, appUserAgent: Identified the browser.
• language, plugin, mimeTypes: options or features supported by the
browser.
• others.

[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]

13. Regular Expression


A Regular Expression (or Regexe in short) is a pattern that accepts a set
of strings that matches the pattern, and rejects the rests. Regexe is
extremely and amazingly powerful in searching and manipulating text
strings and text documents.
Read "Regular Expression" for syntax on regexe.
13.1 Examples
• /^[0_9]+$/ (or /^\d+$/) matches strings with 1 or more digits.
• /^[0_9]{5,8}$/ matches string with 5 to 8 digits.
• /^[a_zA_Z]+$/ matches strings with 1 or more letters.
• /^[0_9a_zA_Z_]+$/ (or /^\w+$/) matches strings with 1 or more digits,
letters or underscore.
13.2 Creating a Regexe in JavaScript
There are two ways to create a regexe in JavaScript:
1. Use a regexe literal enclosed by two forward slashes /.../, for
example,

2. var+identifier+=+/[a_zA_Z_][a_zA_Z_]*/;+
3. var+integer+=+/[1_9][0_9]*|0/;+

var+imageFile+=+/\w+\.(jpg|gif|png)/i;+

4. Call the constructor of the built-in RegExe object, for example,

5. var+pattern+=+new+RegExe("[1_9][0_9]*|0");+

var+ anotherPattern+ =+ new+ RegExe("\w+\.(jpg|gif|png)",+ "i");+ + //+ pattern,+


modifier+

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.

Example 1: Swap first and second words

var+pattern+=+/(\S+)\s+(\S+)/;+
var+input+=+"Hello++world";+
input+=+input.replace(pattern,+"$2+$1");+
++//+result+is+"world+Hello"+

Example 2: Remove HTML markup tags in non-greedy manner

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);+

14.2 Bitwise Operators


JavaScript provides the following bitwise operators are provided for
integers (same syntax as Java):

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)+

You can bookmark the javascript statement (someone called


them bookmarklets). For example, you can write a bookmarklet to change the
background color of a web page, so that the web page is easier to read.

javascript:void(document.body.style.background='#FFF');+

15. JSON (JavaScript Object Notation)


JSON is a data format, similar to XML. JSON is a lightweight, text-based,
human-readable format data-interchange.

JSON supports these data types:


• Number
• Boolean (true or false)
• Array: an ordered, comma-separated sequence of values enclosed in
square bracket.
• Object: an unordered, comma-separated key:value pairs enclosed in
curly bracket.

For example,

[TODO]
PHP provides functions json_encode() and ison_decode() to convert JSON to
array.

Das könnte Ihnen auch gefallen