Lec 4-JavaScript
Lec 4-JavaScript
1
src: https://www.index.dev/blog/12-most-in-demand-programming-languages-to-learn-in-2023
2
Content
• Scripts
• common tasks for client-side scripts
• JavaScript
• data types & expressions
• control statements
• functions & libraries
• date, document, string, array, user-defined classes
3
Client-Side Programming
• 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
4
Common Scripting Tasks
5
JavaScript/ ECMAScript
• ECMA International
• European Computer Manufacturers Association
• Non-profit organization that develops standards in
computer hardware, communications, and
programming languages.
6
JavaScript
7
JavaScript
<html>
• Use <script> tag to add Javascript
<head> code to a page
<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>");
• JavaScript comments similar to
document.write(" <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
8
JavaScript Data Types & Variables
9
JavaScript Declaration
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
document.write("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
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);
document.write("Hello " + userName + 2nd argument: a default value
".") that will appear in the box (in
if (userAge < 18) { case the user enters nothing)
document.write(" Do your parents
know " +. "you are online?");
}
the function returns the value
else { entered by the user in the
document.write(" 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
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)) {
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
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 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(" ");
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~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
16
JavaScript Libraries
<script type="text/javascript"
src="random.js">
</script>
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(" ");
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/CS443/Images/die" +
roll2 + ".gif'/>");
</script>
</div>
</body>
</html>
view page
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.
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 < 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
}
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
Math Object
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
Arrays
31
Array Example
<html>
<head>
<title>Dice Statistics</title>
<script type="text/javascript"
src="http://www.csc.liv.ac.uk/~martin/teaching/CS4
43/JS/random.js">
</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 < rolls.length; 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 < rolls.length; i++) {
document.write("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
32
Arrays (cont.)
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
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
Date Example
<html>
<!–- CS443 js11.html 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 22:55:20 GMT-0600
document.write("<p>" + now + "</p>"); (Central Standard Time) 2002
time = "AM";
hours = now.getHours();
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
document.write("<p>" + hours + ":" +
now.getMinutes() + ":" + 10:55:20 PM
now.getSeconds() + " " +
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 js12.html 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 = Math.round((now-newYear)/1000); milliseconds
days = Math.floor(secs / 86400);
secs -= days*86400; here, determine the number of
hours = Math.floor(secs / 3600); seconds since New Year's day
secs -= hours*3600;
minutes = Math.floor(secs / 60);
(note: January is month 0)
secs -= minutes*60
document.write(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
37
User-Defined Objects
38
Example
<html>
<!–- CS443 js15.html 11.10.2011 -->
<head>
<title>Dice page</title>
<script type="text/javascript" create a Die object using new
src="Die.js">
</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 = die6.roll(); each Die object has its own
roll8 = die8.roll(); properties (numSides & numRolls)
document.write("6-sided: " + roll6 +
" " + Roll(), when called on a particular
"8-sided: " + roll8 + "<br Die, accesses its numSides
/>"); property and updates its NumRolls
}
document.write("<br />Number of rolls: " +
die6.numRolls);
</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:
https://www.w3schools.com/js/exercise_js.asp
•
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:
• https://www.freecodecamp.org/learn/javascript-algorithms-and-
data-structures/
40