0% found this document useful (0 votes)
13 views40 pages

Lec 4-JavaScript

Uploaded by

Thành Chu Văn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views40 pages

Lec 4-JavaScript

Uploaded by

Thành Chu Văn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript

1
src: [Link]

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

2
Content

• Scripts
• common tasks for client-side scripts
• JavaScript
• data types & expressions
• control statements
• functions & libraries
• date, document, string, array, user-defined classes

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

3
Client-Side Programming

• HTML is good for developing static pages


• can specify text/image layout, presentation, links, …
• Web page looks the same each time it is accessed

• Client-side programming
• programs are written in a separate programming (or scripting)
language, e.g., JavaScript,
• programs are embedded in the HTML of a Web page, with
(HTML) tags to identify the program component
• the browser executes the program as it loads the page,
integrating the dynamic output of the program with the static
content of HTML
• could also allow the user (client) to input information and
process it, might be used to validate input before it’s submitted
to a remote server

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

4
Common Scripting Tasks

• adding dynamic features to Web pages


• validation of form data
• image rollovers
• time-sensitive or random page elements
• handling cookies
• defining programs with Web interfaces
• utilize buttons, text boxes, clickable images, prompts,
etc
• limitations of client-side scripting
• since script code is embedded in the page, it is
viewable to the world
• for security reasons, scripts are limited in what they
can do
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

5
JavaScript/ ECMAScript

• ECMA International
• European Computer Manufacturers Association
• Non-profit organization that develops standards in
computer hardware, communications, and
programming languages.

• JavaScript: A general purpose scripting language that


conforms to the ECMAScript specification
• 1997: ECMA-262 standard
• 2023: ECMAScript 14

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

6
JavaScript

• Javascript is a lightweight, interpreted or just-in-time


compiled programming language
• Many non-browser environtments use it such as
[Link], Apache CouchDB, Adobe Acrobat
• Client-side: JS can run on browsers as a scripting
language that allows you to create dynamically updating
content, control multimedia, animate images,…
• Server-side: JS can run on server side with the
appearance of NodeJS – a Javascript runtime
environment.

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

7
JavaScript

<html>
• Use <script> tag to add Javascript
<head> code to a page
<title>JavaScript Page</title>
</head> • [Link] displays text in the
<body>
page
<script type="text/javascript"> § text to be displayed can include
// silly code to demonstrate output
HTML tags
[Link]("<p>Hello world!</p>");
• JavaScript comments similar to
[Link](" <p>How are <br/> " + C++/Java
" <i>you</i>?</p> ");
</script> // starts a single line
<p>Here is some static text as well.</p>
comment
/*…*/ enclose multi-line
</body>
</html> comments

view page

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

8
JavaScript Data Types & Variables

<html> • JavaScript has 7 primitive data types


<!–- CS443 [Link] 16.08.06 -->
String : "foo" 'how do you do”
<head>
<title>Data Types and Number: 12 3.14159 1.5E6
Variables</title>
</head>
<body>
Bigint (ES2020, > 253 -1)
<script type="text/javascript">
var x, y;
Boolean : true false
x= 1024;
y=x; x = "foobar";
Undefined: undefined
[Link]("<p>x = " + y +
"</p>");
Symbol: s = Symbol(‘first name’);
[Link]("<p>x = " + x +
"</p>");
null: null
</script>
</body>
</html>
variable names are sequences of
view page letters, digits, an underscores that start
with a letter or an underscore, case
sensitive

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

9
JavaScript Declaration

• var: function scope or global scope

• let: block scope

• const: same as let, except the user cannot update it

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

10
JavaScript Operators & Control Statements

<html>
<head>
standard C++/Java operators &
<title>Folding Puzzle</title> control statements are provided in
</head> JavaScript
<body>
• +, -, *, /, %, ++, --, …
<script type="text/javascript"> • ==, !=, <, >, <=, >=
const distanceToSun =
93.3e6*5280*12;
• &&, ||, !,===,!==
let thickness = .002; • if , if-else, switch
let foldCount = 0;
while (thickness < distanceToSun) • while, for, do-while, …
{
thickness *= 2;
foldCount++; PUZZLE: Suppose you took a piece
} of paper and folded it in half, then in
[Link]("Number of folds = half again, and so on.
" + foldCount);
How many folds before the thickness
</script>
</body> of the paper reaches from the earth
</html> to the sun?
view page

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

11
Interactive Pages Using Prompt

<html>
<head>
<title>Interactive page</title> crude user interaction can take
</head> place using prompt
<body>
<script type="text/javascript"> 1st argument: the prompt
let userName = prompt("What is your
message that appears in the
name?", "");
let userAge = prompt("Your age?", ""); dialog box
let userAge = parseFloat(userAge);
[Link]("Hello " + userName + 2nd argument: a default value
".") that will appear in the box (in
if (userAge < 18) { case the user enters nothing)
[Link](" Do your parents
know " +. "you are online?");
}
the function returns the value
else { entered by the user in the
[Link](" Welcome dialog box (a string)
friend!");
} if value is a number, must use
</script> parseFloat (or parseInt) to
<p>The rest of the page...</p> convert
</body>
</html> view page
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

12
User-Defined Functions

• function definitions are similar to C++/Java, except:


• no return type for the function (since variables are loosely typed)
• no variable typing for parameters (since variables are loosely typed)
• by-value parameter passing only (parameter gets copy of argument)
function isPrime(n)
// Assumes: n > 0
// Returns: true if n is prime, else false
{
if (n < 2) {
return false;
}
else if (n == 2) {
return true;
}
else {
for (let i = 2; i <= [Link](n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

13
Function Example

<html>
<head>
<title>Prime Tester</title>
<script type="text/javascript">
function isPrime(n)
// Assumes: n > 0
// Returns: true if n is prime
{
// CODE AS SHOWN ON PREVIOUS SLIDE Function definitions (usually) go in
}
the <head> section
</script>
</head>
<body>
<script type="text/javascript"> <head> section is loaded first, so
testNum = parseFloat(prompt("Enter a positive then the function is defined before
integer", "7")); code in the <body> is executed
if (isPrime(testNum)) {
[Link](testNum + " <b>is</b> a prime
number.");
}
else {
[Link](testNum + " <b>is not</b> a prime
number.");
}
</script>
</body>
</html>
view page

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

14
Another Example

<html>
<head>
<title> Random Dice Rolls Revisited</title>
<script type="text/javascript">
function randomInt(low, high)
// Assumes: low <= high
// Returns: random integer in range [low..high]
{
return [Link]([Link]()*(high-low+1)) + low;
}
</script>
</head>
<body>
<div style="text-align: center">
<script type="text/javascript">
roll1 = randomInt(1, 6);
roll2 = randomInt(1, 6);
[Link]("<img src='[Link]
"~martin/teaching/CS443/Images/die" +
roll1 + ".gif'/>");
[Link]("&nbsp;&nbsp;");
[Link]("<img src='[Link]
"~martin/teaching/CS443/Images/die" +
roll2 + ".gif'/>");
</script>
</div>
</body>
</html> view page
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

15
Callback Function

• We can pass functions as parameters to other functions and call


them inside the outer function

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

16
JavaScript Libraries

better still: if you define functions that may be useful to


many pages, store in a separate library file and load the
library when needed load a library using the src
attribute in the script tag (put nothing between the
beginning and ending tags)

<script type="text/javascript"
src="[Link]">
</script>

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

17
Library Example

<html>
<!–- CS443 [Link] 11.10.2011 -->
<head>
<title> Random Dice Rolls Revisited</title>
<script type="text/javascript"
src="[Link]">
</script>
</head>
<body>
<div style="text-align: center">
<script type="text/javascript">
roll1 = randomInt(1, 6);
roll2 = randomInt(1, 6);
[Link]("<img src='[Link]
"~martin/teaching/CS443/Images/die" +
roll1 + ".gif'/>");
[Link]("&nbsp;&nbsp;");
[Link]("<img src='[Link]
"~martin/teaching/CS443/Images/die" +
roll2 + ".gif'/>");
</script>
</div>
</body>
</html>

view page

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

18
Objects

Objects are used to store keyed collections of various data and more
complex entities. An object contains list of properties. A property is a
“key:value” pair, where key is a string and value can be anything.

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology
Objects

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology
Objects

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology
Object references

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology
Garbage collection

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology
Garbage collection

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology
Garbage collection

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology
String Object

• a String object encapsulates a sequence of characters, enclosed in


quotes. Properties include
• length : stores the number of characters in the string
methods include
• charAt(index): returns the character stored at the given index
• substring(start, end): returns the part of the string between
the start (inclusive) and end (exclusive) indices
• toUpperCase(): returns copy of string with letters uppercase
• toLowerCase(): returns copy of string with letters lowercase
to create a string, assign using new or (in this case) just make a
direct assignment (new is implicit)
• word = new String("foo"); word = "foo";
properties/methods are called exactly as in C++/Java
• [Link] [Link](0)

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

26
String example: Palindromes

function strip(str)
// Assumes: str is a string suppose we want to test whether a
// Returns: str with all but letters removed
{
word or phrase is a palindrome
let copy = "";
for (let i = 0; i < [Link]; i++) {
if (([Link](i) >= "A" && [Link](i) <= "Z") noon Radar
|| Madam, I'm Adam.
([Link](i) >= "a" && [Link](i) <= "z"))
{
copy += [Link](i);
}
} must strip non-letters out of the word or
return copy; phrase
}

function isPalindrome(str) make all chars uppercase in order to be


// Assumes: str is a string
// Returns: true if str is a palindrome, else false
case-insensitive
{
str = strip([Link]());
finally, traverse and compare chars from
for(let i = 0; i < [Link]([Link]/2); i++) { each end
if ([Link](i) != [Link]([Link]-i-1)) {
return false;
}
}
return true;
}

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

27
<html>
<!–- CS443 [Link] 11.10.2011 -->
<head>
<title>Palindrome Checker</title>
<script type="text/javascript">
function strip(str)
{
// CODE AS SHOWN ON PREVIOUS SLIDE
}
function isPalindrome(str)
{
// CODE AS SHOWN ON PREVIOUS SLIDE
}
</script>
</head>
<body>
<script type="text/javascript">
text = prompt("Enter a word or phrase", "Madam, I'm Adam");
if (isPalindrome(text)) {
[Link]("'" + text + "' <b>is</b> a palindrome.");
}
else {
[Link]("'" + text + "' <b>is not</b> a
palindrome.");
}
</script>
</body>
</html>
view page

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

28
Math Object

<html> the built-in Math object contains


<!–- CS443 [Link] 08.10.10 -->
<head> functions and constants
<title>Random Dice Rolls</title>
</head>
<body>
[Link]
<div style="text-align:center"> [Link]
<script type="text/javascript">
let roll1 = [Link]([Link]()*6) + 1;
[Link]
let roll2 = [Link]([Link]()*6) + 1; [Link]
[Link]("<img [Link]
src='[Link]
"~martin/teaching/CS443/Images/die" + [Link]
roll1 + ".gif‘ alt=‘dice showing ‘ + [Link]
roll1 />");
[Link]("&nbsp;&nbsp;");
[Link]
[Link]("<img
src='[Link]
"~martin/teaching/CS443/Images/die" +
[Link]
roll2 + ".gif‘ alt=‘dice showing ‘ + Math.E
roll2 />");
</script>
</div> [Link] function returns a real
</body>
</html>
number in [0..1)
view page

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

29
Math Object

• ceil(4.7)=? 5
• floor(4.7)=? 4
• round(4.7)=? 5

• ceil(4.2)=? 5
• floor(4.2)=? 4
• round(4.2)=? 4

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

30
Arrays

• Arrays store a sequence of items, accessible via an index


• since JavaScript is loosely typed, elements do not have to be the same
type
• to create an array, allocate space using new (or can assign directly)
items = new Array(10); // allocates space for 10 items
items = new Array(); // if no size given, will adjust
dynamically
items = [0,0,0,0,0,0,0,0,0,0]; // can assign size & values []
• to access an array element, use [] (as in C++/Java)
for (i = 0; i < 10; i++) {
items[i] = 0; // stores 0 at each index
}
• the length property stores the number of items in the array
for (i = 0; i < [Link]; i++) {
[Link](items[i] + "<br>"); // displays elements
}

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

31
Array Example
<html>
<head>
<title>Dice Statistics</title>
<script type="text/javascript"
src="[Link]
43/JS/[Link]">
</script>
</head>
<body> suppose we want to
<script type="text/javascript"> simulate dice rolls and verify
const numRolls = 60000; even distribution
const diceSides = 6;
let rolls = new Array(dieSides+1);
for (i = 1; i < [Link]; i++) { keep an array of counters:
rolls[i] = 0;
} -initialize each count to 0
for(i = 1; i <= numRolls; i++) {
rolls[randomInt(1, dieSides)]++; -each time you roll X,
} increment rolls[X]
for (i = 1; i < [Link]; i++) {
[Link]("Number of " + i + "'s = "
+ -display each counter
rolls[i] + "<br />");
}
</script> view page
</body>TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG

</html>School of Inform ation and Com m unication Technology

32
Arrays (cont.)

• Arrays have predefined methods that allow them to be used as


stacks, queues, or other common programming data structures.
var stack = new Array();
[Link]("blue");
[Link](12); // stack is now the array ["blue", 12]
[Link]("green"); // stack = ["blue", 12, "green"]
var item = [Link](); // item is now equal to "green"

var q = [1,2,3,4,5,6,7,8,9,10];
item = [Link](); // item is now equal to 1, remaining
// elements of q move down one position
// in the array, e.g. q[0] equals 2
[Link](125); // q is now the array [125,2,3,4,5,6,7,8,9,10]
[Link](244); // q = [125,2,3,4,5,6,7,8,9,10,244]

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

33
Date Object

• String & Array are the most commonly used objects in JavaScript
• other, special purpose objects also exist
• the Date object can be used to access the date and time
• to create a Date object, use new & supply year/month/day/… as desired
today = new Date(); // sets to current date & time
newYear = new Date(2002,0,1); //sets to Jan 1, 2002
12:00AM
• methods include:
[Link]() can access individual components of a date
[Link]() number (0, 11)
[Link]() number (1, 31)
[Link]() number (0, 23)
[Link]() number (0, 59)
[Link]() number (0, 59)
[Link]() number (0, 999)

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

34
Date Example
<html>
<!–- CS443 [Link] 16.08.2006 -->
<head>
<title>Time page</title>
</head> by default, a date will be displayed
<body>
in full, e.g.,
Time when page was loaded:
<script type="text/javascript">
now = new Date(); Sun Feb 03 [Link] GMT-0600
[Link]("<p>" + now + "</p>"); (Central Standard Time) 2002
time = "AM";
hours = [Link]();
if (hours > 12) { can pull out portions of the date
hours -= 12;
using the methods and display as
time = "PM"
} desired
else if (hours == 0) {
hours = 12; here, determine if "AM" or "PM"
} and adjust so hour between 1-12
[Link]("<p>" + hours + ":" +
[Link]() + ":" + [Link] PM
[Link]() + " " +
time + "</p>");
</script>
</body>
</html> view page
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

35
Another Example
<html>
<!–- CS443 [Link] 12.10.2012 -->
<head>
<title>Time page</title>
</head>
<body>
<p>Elapsed time in this year:
<script type="text/javascript">
now = new Date(); you can add and subtract Dates:
newYear = new Date(2012,0,1); the result is a number of
secs = [Link]((now-newYear)/1000); milliseconds
days = [Link](secs / 86400);
secs -= days*86400; here, determine the number of
hours = [Link](secs / 3600); seconds since New Year's day
secs -= hours*3600;
minutes = [Link](secs / 60);
(note: January is month 0)
secs -= minutes*60
[Link](days + " days, " + divide into number of days,
hours + " hours, " + hours, minutes and seconds
minutes + " minutes,
and " +
secs + " seconds.");
</script>
</p>
</body>
</html>
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG view page
School of Inform ation and Com m unication Technology

36
Document Object

Internet Explorer, Firefox, Opera, etc. allow you to access information


about an HTML document using the document object
<html> [Link](…)
<!–- CS443 [Link] 2.10.2012 -->
<head> method that displays text in the
<title>Documentation page</title> page
</head>
<body>
<table width="100%"> [Link]
<tr>
<td><i> property that gives the location of
<script type="text/javascript"> the HTML document
[Link]([Link]);
</script>
</i></td>
[Link]
<td style="text-align: right;"><i>
<script type="text/javascript"> property that gives the date & time
[Link]([Link]); the HTML document was last
</script>
</i></td> changed
</tr>
</table>
</body>
</html> view page

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

37
User-Defined Objects

• User can create a class by using keyword “class”

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

38
Example
<html>
<!–- CS443 [Link] 11.10.2011 -->
<head>
<title>Dice page</title>
<script type="text/javascript" create a Die object using new
src="[Link]">
</script> (similar to String and Array)
</head>
<body> here, the argument to Die
<script type="text/javascript">
die6 = new Die(6); die8 = new Die(8); initializes numSides for that
roll6 = -1; // dummy value to start loop particular object
roll8 = -2; // dummy value to start loop
while (roll6 != roll8) {
roll6 = [Link](); each Die object has its own
roll8 = [Link](); properties (numSides & numRolls)
[Link]("6-sided: " + roll6 +
"&nbsp;&nbsp;&nbsp;&nbsp;" + Roll(), when called on a particular
"8-sided: " + roll8 + "<br Die, accesses its numSides
/>"); property and updates its NumRolls
}
[Link]("<br />Number of rolls: " +
[Link]);
</script>
</body>
</html>

view page
TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Inform ation and Com m unication Technology

39
• Ex 1. Complete 09 exercises of section DOM at:
[Link]

Ex 2. Create a registration page including full name, phone number,
and email. Use JavaScript to check users’ inputs:
• Name: is not empty
• Phone number: contains 10 or 11 numbers
• Email: follows email address format
• Ex 3. Complete 16 exercises of section Basic Algorithm Scripting
at:

• [Link]
data-structures/

TRƯ Ờ NG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Inform ation and Com m unication Technology

40

You might also like