0% found this document useful (0 votes)
6 views

Handout 04. Javascript

Uploaded by

Ha Cao Thu
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)
6 views

Handout 04. Javascript

Uploaded by

Ha Cao Thu
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
You are on page 1/ 21

4/10/2024

JavaScript

src: https://bootcamp.berkeley.edu/blog/most-in-demand-programming-languages/ 2

1
4/10/2024

Content

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

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

2
4/10/2024

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
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
• 2022: ECMAScript 13 was released in June 2022

3
4/10/2024

JavaScript
• Javascript is a lightweight, interpreted or just-in-time compiled
programming language
• Many non-browser environtments use it such as Node.js,
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.
7

JavaScript
<html>
<!–- CS443 js01.html 16.08.06 --> • Use <script> tag to add Javascript
code to a page
<head>
<title>JavaScript Page</title>
</head> • document.write displays text in the
<body> page
<script type="text/javascript"> ▪ text to be displayed can include
// silly code to demonstrate output
HTML tags
document.write("<p>Hello world!</p>");

document.write(" <p>How are <br/> " + • JavaScript comments similar to


" <i>you</i>?</p> "); C++/Java
</script>

<p>Here is some static text as well.</p> // starts a single line comment


</body> /*…*/ enclose multi-line comments
</html>

view page

4
4/10/2024

JavaScript Data Types & Variables


<html>
<!–- CS443 js02.html 16.08.06 --> • JavaScript has 7 primitive data types
<head>
String : "foo" 'how do you do?' "I said 'hi'."
<title>Data Types and Variables</title> Number: 12 3.14159 1.5E6
</head>
<body> Bigint (ES2020, số > 253 -1): 9007199254740991n
<script type="text/javascript">
var x, y; Boolean : true false
x= 1024;
Undefined: undefined
y=x; x = "foobar";
document.write("<p>x = " + y + "</p>"); Symbol: s = Symbol(‘first name’);
document.write("<p>x = " + x + "</p>");
</script> null: null
</body>
</html>
variable names are sequences of letters, digits, an
view page underscores that start with a letter or an
underscore, case sensitive

JavaScript Declaration
• var: function scope or global scope

• let: block scope

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


10

10

5
4/10/2024

JavaScript Operators & Control Statements


standard C++/Java operators &
<html>
<!–- CS443 js03.html 08.10.10 --> control statements are provided
<head>
in JavaScript
<title>Folding Puzzle</title> • +, -, *, /, %, ++, --, …
</head> • ==, !=, <, >, <=, >=
<body> • &&, ||, !,===,!==
<script type="text/javascript"> • if , if-else, switch
const distanceToSun = 93.3e6*5280*12;
let thickness = .002; • while, for, do-while, …

let foldCount = 0;
while (thickness < distanceToSun) { PUZZLE: Suppose you took a
thickness *= 2;
foldCount++;
piece of paper and folded it in
} half, then in half again, and so
document.write("Number of folds = " +
foldCount);
on.
</script> How many folds before the
</body>
</html>
thickness of the paper reaches
from the earth to the sun?
view page
11

11

Interactive Pages Using Prompt


<html> crude user interaction can
<!-- CS443 js05.html 08.10.10 -->
<head> take place using prompt
<title>Interactive page</title>
</head>
<body> 1st argument: the prompt
<script type="text/javascript"> message that appears in the
let userName = prompt("What is your name?",
dialog box
"");
let userAge = prompt("Your age?", "");
let userAge = parseFloat(userAge); 2nd argument: a default value
document.write("Hello " + userName + ".") that will appear in the box (in
if (userAge < 18) {
document.write(" Do your parents know "
case the user enters nothing)
+. "you are online?");
} the function returns the value
else {
entered by the user in the dialog
document.write(" Welcome friend!");
} box (a string)
</script>
<p>The rest of the page...</p> if value is a number, must use
</body>
</html> parseFloat (or parseInt) to
convert

view page 12

12

6
4/10/2024

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 <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
} 13

13

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

14

7
4/10/2024

Another Example
<html>
<!–- CS443 js07.html 11.10.2011 -->
<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 Math.floor(Math.random()*(high-low+1)) + low;
}
</script>
</head>
<body>
<div style="text-align: center">
<script type="text/javascript">
roll1 = randomInt(1, 6);
roll2 = randomInt(1, 6);
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/CS443/Images/die" +
roll1 + ".gif'/>");
document.write("&nbsp;&nbsp;");
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/CS443/Images/die" +
roll2 + ".gif'/>");
</script>
</div>
</body>
</html> view page 15

15

Callback Function
• We can pass functions as parameters to other functions and
call them inside the outer function

16

16

8
4/10/2024

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="random.js">
</script>

17

17

Library Example
<html>
<!–- CS443 js08.html 11.10.2011 -->
<head>
<title> Random Dice Rolls Revisited</title>
<script type="text/javascript"
src="random.js">
</script>
</head>
<body>
<div style="text-align: center">
<script type="text/javascript">
roll1 = randomInt(1, 6);
roll2 = randomInt(1, 6);
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/CS443/Images/die" +
roll1 + ".gif'/>");
document.write("&nbsp;&nbsp;");
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/CS443/Images/die" +
roll2 + ".gif'/>");
</script>
</div>
</body>
view page
</html>
18

18

9
4/10/2024

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.

19

Objects

20

10
4/10/2024

Objects

21

Object references

22

11
4/10/2024

Garbage collection

23

Garbage collection

24

12
4/10/2024

Garbage collection

25

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
• word.length word.charAt(0)

26

26

13
4/10/2024

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 < str.length; i++) {
if ((str.charAt(i) >= "A" && str.charAt(i) <= "Z") noon Radar
|| Madam, I'm Adam.
(str.charAt(i) >= "a" && str.charAt(i) <= "z"))
{
copy += str.charAt(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 case-insensitive
// Returns: true if str is a palindrome, else false
{
str = strip(str.toUpperCase());
finally, traverse and compare chars from
for(let i = 0; i < Math.floor(str.length/2); i++) { each end
if (str.charAt(i) != str.charAt(str.length-i-1)) {
return false;
}
}
return true;
} 27

27

<html>
<!–- CS443 js09.html 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)) {
document.write("'" + text + "' <b>is</b> a palindrome.");
}
else {
document.write("'" + text + "' <b>is not</b> a
palindrome.");
}
</script>
</body>
</html>
view page

28

28

14
4/10/2024

Math Object
<html> the built-in Math object contains functions
<!–- CS443 js04.html 08.10.10 -->
<head> and constants
<title>Random Dice Rolls</title>
</head>
<body>
Math.sqrt
<div style="text-align:center"> Math.pow
<script type="text/javascript"> Math.abs
let roll1 = Math.floor(Math.random()*6) + 1;
let roll2 = Math.floor(Math.random()*6) + 1; Math.max
document.write("<img Math.min
src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/CS443/Images/die" + Math.floor
roll1 + ".gif‘ alt=‘dice showing ‘ + Math.ceil
roll1 />");
document.write("&nbsp;&nbsp;"); Math.round
document.write("<img
src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/CS443/Images/die" +
Math.PI
roll2 + ".gif‘ alt=‘dice showing ‘ + Math.E
roll2 />");
</script>
</div> Math.random function returns a real
</body>
</html>
number in [0..1)

view page
29

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

30

30

15
4/10/2024

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 < items.length; i++) {
document.write(items[i] + "<br>"); // displays elements
}

31

31

Array Example
<html>
<!–- CS443 js10.html 11.10.2011 -->
<head>
<title>Dice Statistics</title>
<script type="text/javascript"
src="http://www.csc.liv.ac.uk/~martin/teaching/CS443/JS/rand suppose we want to simulate dice
om.js">
</script>
rolls and verify even distribution
</head>
<body> keep an array of counters:
<script type="text/javascript">
const numRolls = 60000;
const diceSides = 6; -initialize each count to 0
let rolls = new Array(dieSides+1);
for (i = 1; i < rolls.length; i++) {
rolls[i] = 0; -each time you roll X, increment
} rolls[X]
for(i = 1; i <= numRolls; i++) {
rolls[randomInt(1, dieSides)]++;
} -display each counter
for (i = 1; i < rolls.length; i++) {
document.write("Number of " + i + "'s = " +
rolls[i] + "<br />");
}
</script>
</body> view page
</html> 32

32

16
4/10/2024

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();
stack.push("blue");
stack.push(12); // stack is now the array ["blue", 12]
stack.push("green"); // stack = ["blue", 12, "green"]
var item = stack.pop(); // item is now equal to "green"

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

33

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:
newYear.getFullYear() can access individual components of a date
newYear.getMonth() number (0, 11)
newYear.getDay() number (1, 31)
newYear.getHours() number (0, 23)
newYear.getMinutes() number (0, 59)
newYear.getSeconds() number (0, 59)
newYear.getMilliseconds() number (0, 999)

34

34

17
4/10/2024

Date Example
<html>
<!–- CS443 js11.html 16.08.2006 -->
<head> by default, a date will be displayed in full,
<title>Time page</title>
</head> e.g.,
<body>
Time when page was loaded: Sun Feb 03 22:55:20 GMT-0600 (Central
<script type="text/javascript">
now = new Date(); Standard Time) 2002
document.write("<p>" + now + "</p>");
time = "AM";
hours = now.getHours();
if (hours > 12) { can pull out portions of the date using the
hours -= 12; methods and display as desired
time = "PM"
}
else if (hours == 0) { here, determine if "AM" or "PM" and
hours = 12; adjust so hour between 1-12
}
document.write("<p>" + hours + ":" +
now.getMinutes() + ":" + 10:55:20 PM
now.getSeconds() + " " +
time + "</p>");
</script>
</body>
view page
</html>
35

35

Another Example
<html>
<!–- CS443 js12.html 12.10.2012 -->
<head>
<title>Time page</title>
</head> you can add and subtract Dates:
<body> the result is a number of milliseconds
<p>Elapsed time in this year:
<script type="text/javascript">
now = new Date(); here, determine the number of
newYear = new Date(2012,0,1); seconds since New Year's day
secs = Math.round((now-newYear)/1000);
days = Math.floor(secs / 86400);
(note: January is month 0)
secs -= days*86400;
hours = Math.floor(secs / 3600); divide into number of days, hours,
secs -= hours*3600;
minutes = Math.floor(secs / 60);
minutes and seconds
secs -= minutes*60
document.write(days + " days, " +
hours + " hours, " +
minutes + " minutes, and " +
secs + " seconds.");
</script>
</p>
</body> view page
</html>
36

36

18
4/10/2024

Document Object
Internet Explorer, Firefox, Opera, etc. allow you to access information about an HTML document using the
document object
<html>
<!–- CS443 js13.html 2.10.2012 -->
<head> document.write(…)
<title>Documentation page</title>
method that displays text in the page
</head>
<body>
<table width="100%">
<tr> document.URL
<td><i> property that gives the location of the
<script type="text/javascript">
document.write(document.URL); HTML document
</script>
</i></td>
<td style="text-align: right;"><i> document.lastModified
<script type="text/javascript">
document.write(document.lastModified); property that gives the date & time the
</script> HTML document was last changed
</i></td>
</tr>
</table>
</body>
</html>
view page 37

37

User-Defined Objects
• User can create a class by using keyword “class”

38

38

19
4/10/2024

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

39

HTML Events: onclick

<!DOCTYPE html> using onclick to catch event of mouse click


<html>
<body>
<h1>JavaScript HTML Events</h1> Remember the events in HTML!!!
<h2>The onclick Attribute</h2>

<h2 onclick="this.innerHTML='Ooops!’”> Other events:


Click on this text!</h2> • onmouseover and onmouseout events can be used
</body> to trigger a function when the user mouses over, or
</html> out of, an HTML element
• onload and onunload events are triggered when the
user enters or leaves the page.
view page • oninput event is often to some action while the user
input data.
• onchange event is often used in combination with
validation of input fields.

40

40

20
4/10/2024

HTML Events: onclick (cont.)

<!DOCTYPE html> Applying javascript function in catching


<html>
<body> event, for complicate manipulation:
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
• Defining function
<p>Click the button to display the date.</p> • Call the function by event fired
<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>

</body>
</html>

view page
41

41

HTML Form input values


<!DOCTYPE html>
<html><head>
<script> • Catching onsubmit event
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
• Access the form’s fields value
if (x == "") {
alert("Name must be filled out"); • Note: onclick event of the button
return false;
} can be used, instead of form event
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>

<form name="myForm" action="/action_page.php" onsubmit="return


validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

view page 42

42

21

You might also like