JavaScript
1
Most used programming languages as of 2024
src: [Link]
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
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ƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
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ƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
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ƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
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: ECMAScript 1
• 2023: ECMAScript 14
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
6
JavaScript
• JavaScript is mainly interpreted, but modern JavaScript
engines, like V8 in Google Chrome, use JIT (Just-In-
Time) compilation to boost performance.
• 1. Interpreter: An interpreter runs instructions directly from
the programming language without changing them into
machine code first.
• 2. Compiler: A compiler changes the entire program into
object code (or binary code) before running. This code can
then be run by the machine.
• 3. JIT Compiler: A JIT compiler converts code into byte code
first. Then, at runtime, it changes the byte code into
machine-readable code, which makes the program run faster.
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
7
JavaScript
• 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ƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
8
JavaScript
<!DOCTYPE html> • Use <script> tag to add
<html>
<head>
Javascript code to a page
<title>JavaScript Page</title>
</head> • [Link]
▪ displays text in the page
<body>
<script type="text/javascript">
▪ text can include HTML
[Link]("<p>Hello tags
world!</p>");
[Link](" <p>How are
you?</p> ");
</script>
<p>Here is some static text.</p>
</body>
</html>
[Link]
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
9
JavaScript Data Types & Variables
<script>
// Number: • JavaScript has 8 data types
let weight = 7.5; String
// String: Number
let color = "Yellow"; Bigint
Boolean
// Booleans Undefined: undefined
let x = true;
Null: null
// Object: Symbol
const person = {firstName:"John", Object
lastName:"Doe"};
// Array object:
• variable names contain
const cars = ["Saab", "Volvo"]; letters, digits, an
underscores that start with
// Date object: a letter or an underscore,
const date = new Date("2024-09-25");
</script>
case sensitive
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
10
JavaScript Data Types & Variables
• Same variable can be used to hold different data types:
<script>
let x; // Now x is undefined
x = 5; // Now x is a Number
x = ”A"; // Now x is a String
</script>
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
11
JavaScript Declaration
• var: function scope or global scope
• let: block scope
• const: same as let, except the user cannot update it
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
12
JavaScript Operators & Control Statements
<!DOCTYPE html>
<html>
<body> Operators & control
<script type="text/javascript"> statements:
const distanceToSun = 93.3e6
* 5280 * 12;
let thickness = .002;
+, -, *, /, %, ++, --, …
let foldCount = 0;
while (thickness < ==, !=, <, >, <=, >=
distanceToSun) {
thickness *= 2; &&, ||, !,===,!==
foldCount++;
}
[Link]("Number of if , if-else, switch
folds = " +foldCount);
</script>
while, for, do-while, …
</body>
</html>
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
13
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)
{
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ƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
14
Function Example
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function isPrime(n)
// Assumes: n > 0
// Returns: true if n is prime
{
// CODE AS SHOWN ON PREVIOUS SLIDE
}
</script>
</head>
<body>
<script type="text/javascript">
testNum = parseFloat(prompt("Enter a positive integer", "7"));
if (isPrime(testNum)) {
[Link](testNum + " <b>is</b> a prime number.");
}
else {
[Link](testNum + " <b>is not</b> a prime number.");
}
</script>
</body>
</html>
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
15
Another Example
<!DOCTYPE html>
<html>
<head>
<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>
<script type="text/javascript">
roll1 = randomInt(1, 6);
roll2 = randomInt(1, 6);
[Link]("<img src='" + roll1 + ".gif'/>");
[Link]("<br/>");
[Link]("<img src='" + roll2 + ".gif'/>");
</script>
</body>
</html>
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
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ƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
17
Library Example
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="[Link]">
</script>
</head>
<body>
<script type="text/javascript">
roll1 = randomInt(1, 6);
roll2 = randomInt(1, 6);
[Link]("<img src='" + roll1 + ".gif'/>");
[Link]("<br/>");
[Link]("<img src='" + roll2 + ".gif'/>");
</script>
</body>
</html>
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
18
Callback Function
• We can pass functions as parameters to other functions
and call them inside the outer function
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
19
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ƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
Objects
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
Objects
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
Object references
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
Garbage collection
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
Garbage collection
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
Garbage collection
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
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ƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
27
String example: Palindromes
function strip(str) suppose we want to
{
let copy = "";
test whether a word
for (let i = 0; i < [Link]; i++) { or phrase is a
if (([Link](i) >= "A" && [Link](i) <= "Z") || palindrome
([Link](i) >= "a" && [Link](i) <= "z")) {
copy += [Link](i); noon Radar
} Madam, I'm Adam.
}
return copy;
} - must strip non-
function isPalindrome(str)
letters
// Assumes: str is a string - make all chars
// Returns: true if str is a palindrome, else false uppercase in order to
{
str = strip([Link]()); be case-insensitive
- finally, traverse and
for(let i = 0; i < [Link]([Link]/2); i++) {
if ([Link](i) != [Link]([Link]-i-1)) { compare chars from
return false; each end
}
}
return true;
}
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
28
<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>
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
29
Math Object
<html>
<head>
<title>Random Dice Rolls</title> the built-in Math object contains
</head> functions and constants
<body>
<div style="text-align:center"> [Link]
<script type="text/javascript"> [Link]
let roll1 = [Link]([Link]()*6) + 1; [Link]
let roll2 = [Link]([Link]()*6) + 1; [Link]
[Link]("<img src=‘" + [Link]
roll1 + ".gif‘ alt=‘dice showing ‘ + [Link]
roll1 />"); [Link]
[Link]("<img src=‘" + [Link]
roll2 + ".gif‘ alt=‘dice showing ‘ +
roll2 />"); [Link]
</script> Math.E
</div>
</body> [Link] function returns a real
</html> number in [0..1)
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
30
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ƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
31
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ƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
32
Array Example
<html>
<head>
<title>Dice Statistics</title>
<script type="text/javascript"
src="[Link]">
</script>
</head> suppose we want to simulate
<body> dice rolls and verify even
<script type="text/javascript"> distribution
const numRolls = 60000;
const diceSides = 6; keep an array of counters:
let rolls = new Array(dieSides+1);
for (i = 1; i < [Link]; i++) { -initialize each count to 0
rolls[i] = 0;
} -each time you roll X, increment
for(i = 1; i <= numRolls; i++) { rolls[X]
rolls[randomInt(1, dieSides)]++;
} -display each counter
for (i = 1; i < [Link]; i++) {
[Link]("Number of " + i + "'s = " +
rolls[i] + "<br />");
}
</script>
</body>
</html>
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
33
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ƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
34
Date Object
• the Date object can be used to access the date and time
• to create a Date object, use new & supply year/month/day/…
today = new Date(); // sets to current date & time
newYear = new Date(2024,0,1); //sets to Jan 1, 2024 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ƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
35
Date Example
<body>
Time when page was loaded:
<script type="text/javascript">
now = new Date(); by default, a date will be
[Link]("<p>" + now + "</p>"); displayed in full, e.g.,
time = "AM";
hours = [Link](); Wed, Sep 25 22:55:20 2024
if (hours > 12) {
hours -= 12; can pull out portions of the date
time = "PM"
using the methods and display
}
else if (hours == 0) { as desired
hours = 12;
} here, determine if "AM" or
[Link]("<p>" + hours + ":" + "PM" and adjust so hour
[Link]() + ":" + between 1-12
[Link]() + " " +
time + "</p>"); 10:55:20 PM
</script>
</body>
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
36
Another Example
<body>
<p>Elapsed time in this year:
<script type="text/javascript">
now = new Date();
newYear = new Date(2024,0,1);
secs = [Link]((now-newYear)/1000);
days = [Link](secs / 86400);
secs -= days*86400;
hours = [Link](secs / 3600);
secs -= hours*3600;
minutes = [Link](secs / 60);
secs -= minutes*60
[Link](days + " days, " +
hours + " hours, " +
minutes + " minutes, and " +
secs + " seconds.");
</script>
</p>
</body>
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
37
Document Object
<body>
<table width="100%"> [Link](…)
<tr> method that displays text in
<td><i> the page
<script type="text/javascript">
[Link]([Link]);
</script> [Link]
</i></td> property that gives the
<td style="text-align: right;"><i> location of the HTML
<script type="text/javascript"> document
[Link]([Link]);
</script> [Link]
</i></td>
property that gives the date &
</tr>
time the HTML document was
</table>
last changed
</body>
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
38
User-Defined Objects
• User can create a class by using keyword “class”
TRƯỜN G CÔNG NGHỆ TH ÔN G TIN VÀ TRU YỀN TH ÔN G
Scho ol of In fo rmation a nd Co mmuni cation Tech nol ogy
39