Handout 04. Javascript
Handout 04. Javascript
JavaScript
Content
https://www.javascripttutorial.net
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology
1
10/24/2024
https://www.index.dev/blog/12-most-in-demand-programming-languages-to-learn-in-2023
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology
4
2
10/24/2024
https://www.javascripttutorial.net/nodejs-tutorial
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology
5
3
10/24/2024
JavaScript History
❑ In 1995, JavaScript was developed by Brendan Eich, a Netscape developer. Initially named
Mocha, it was later renamed to LiveScript.
❑ Integrated in Netscape Navigator (which was one of the first web browser) and renamed to
JavaScript (by influence from Java language).
❑ Browser war!!! Netscape launched JavaScript 1.1 in Netscape Navigator 3. Microsoft
introduced Internet Explorer 3 (IE 3) with its own JavaScript implementation called JScript.
❑ In 1997, JavaScript 1.1 was proposed to the European Computer Manufacturers Association
(ECMA) as a proposal of ECMAScript (often pronounced Ek-ma-script).
❑ International Organization for Standardization and International Electrotechnical Commissions
(ISO/IEC) adopted ECMAScript (ISO/IEC-16262).
❑ 2022: ECMAScript 13 was released in June 2022
❑ Need to check language capabilities (such as OOP) by JavaScript version and browser support.
4
10/24/2024
JavaScript IDE
https://code.visualstudio.com
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology
VS Code Setting
10
10
5
10/24/2024
11
11
12
12
6
10/24/2024
Js Fundamentals
❑ Syntax
❑ Variables
❑ Data Types
❑ Array
❑ Operators
JavaScript ❑ Control Flow
13
13
❑ Blocks: { }
❑ Identifiers: Case-sensitive. The message is different from the Message.
❑ Comments: // (inline) and /* … */ (block)
14
14
7
10/24/2024
Variables
❑ Declare a variable
❖ var (global scope)
❖ let (block scope)
var message;
for (let i = 0; i < 5; i++) {
console.log("Inside the loop:", i);
}
15
15
Data Types
16
16
8
10/24/2024
Array
console.log(mountains[1]); // 'Fuji’
console.log(mountains.length); // 3
17
17
Operators
18
18
9
10/24/2024
Control Flow
❑ if / if else
❑ ternary operator (:?)
❑ switch case
❑ while
❑ do while
JavaScript ❑ for
❑ break
❑ continue
❑ comma operator
19
19
20
20
10
10/24/2024
21
21
22
22
11
10/24/2024
Comma operator: ,
❑ Batch execution
❑ Syntax
❖ leftExpression, rightExpression
❖ execute from left to right, and returns the value of the
right expression
❑ Examples
❖ let x = 10;
let y = (x++, x + 1); Output:
console.log(x, y); 11 12
23
23
Objects
❑ Overview
❑ Object creation & calculation
❑ Object reference
❑ Garbage collection
❑ Some particular object: String, Math, Date, Array, etc…
JavaScript
24
24
12
10/24/2024
Objects Overview
❑ 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.
25
26
13
10/24/2024
Object references
27
Garbage collection
28
14
10/24/2024
29
30
15
10/24/2024
31
31
String Object
➢ substring(start, end): returns the part of the string between the start (inclusive) and
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)
32
16
10/24/2024
function strip(str)
suppose we want to test whether a // Assumes: str is a string
// 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 (str.charAt(i) >= "a" && str.charAt(i) <= "z")) {
Madam, I'm Adam. }
copy += str.charAt(i);
}
return copy;
}
must strip non-letters out of the word or function isPalindrome(str)
phrase // Assumes: str is a string
// Returns: true if str is a palindrome, else false
{
str = strip(str.toUpperCase());
make all chars uppercase in order to be
for(let i = 0; i < Math.floor(str.length/2); i++) {
case-insensitive if (str.charAt(i) != str.charAt(str.length-i-1)) {
return false;
}
}
finally, traverse and compare chars from return true;
}
each end
33
<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
view page
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology
34
34
17
10/24/2024
Math Object
view page
Math.random function returns a real
number in [0..1)
35
Math Object
❑ ceil(4.7)=?
5
❑ floor(4.7)=?
❑ round(4.7)=? 4
5
❑ ceil(4.2)=?
❑ floor(4.2)=?
❑ round(4.2)=? 5
4
4
36
18
10/24/2024
Array Object
37
Array Example
<html>
<!–- CS443 js10.html 11.10.2011 -->
suppose we want to simulate dice <head>
rolls and verify even distribution <title>Dice Statistics</title>
<script type="text/javascript"
src="http://www.csc.liv.ac.uk/~martin/teaching/CS443/JS/random.js">
</script>
keep an array of counters: </head>
<body>
<script type="text/javascript">
-initialize each count to 0 const numRolls = 60000;
const diceSides = 6;
let rolls = new Array(dieSides+1);
for (i = 1; i < rolls.length; i++) {
-each time you roll X, increment rolls[i] = 0;
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>
</html>
view page
view page
38
19
10/24/2024
Arrays (cont.)
• Arrays have predefined methods that allow them to be used as stacks, queues, or other
common programming data structures.
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]
39
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)
40
20
10/24/2024
Date Example
<html>
by default, a date will be displayed in full, <!–- CS443 js11.html 16.08.2006 -->
e.g., <head>
<title>Time page</title>
</head>
<body>
Sun Feb 03 22:55:20 GMT-0600 (Central Time when page was loaded:
<script type="text/javascript">
Standard Time) 2002 now = new Date();
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) {
hours = 12;
here, determine if "AM" or "PM" and }
document.write("<p>" + hours + ":" +
adjust so hour between 1-12 now.getMinutes() + ":" +
now.getSeconds() + " " +
time + "</p>");
10:55:20 PM </script>
</body>
</html>
view page
view page
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology
41
41
Another Example
<html>
you can add and subtract Dates: <!–- CS443 js12.html 12.10.2012 -->
<head>
the result is a number of milliseconds <title>Time page</title>
</head>
<body>
here, determine the number of <p>Elapsed time in this year:
<script type="text/javascript">
seconds since New Year's day now = new Date();
newYear = new Date(2012,0,1);
(note: January is month 0) secs = Math.round((now-newYear)/1000);
days = Math.floor(secs / 86400);
secs -= days*86400;
divide into number of days, hours, hours = Math.floor(secs / 3600);
secs -= hours*3600;
minutes and seconds minutes = Math.floor(secs / 60);
secs -= minutes*60
document.write(days + " days, " +
hours + " hours, " +
minutes + " minutes, and " +
secs + " seconds.");
</script>
</p>
</body>
</html>
view page
view page
42
21
10/24/2024
Document Object
view page
HTML document was last changed
43
44
44
22
10/24/2024
Person.prototype.getName = function () {
return this.name;
};
❑ ES6 OOP
❖ class declaration
❖ class Person {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
source: https://www.w3schools.com/js/js_versions.asp
45
45
46
46
23
10/24/2024
console.log(john.getName());
john.setName("Elon Musk");
console.log(john.getName());
47
47
❑ class Point {
#x; //private ❑ Console debug
#y; //private
static displayName = "Point"; // static field
constructor(x, y) {
this.#x = x;
this.#y = y;
}
getX() {
return this.#x;
}
getY() {
return this.#y;
}
diplay() {
console.log("(" + this.#x + "," + this.#y + ")");
}
static distance(a, b) {
let dx = a.getX() - b.getY();
let dy = a.getY() - b.getY();
return Math.hypot(dx, dy);
} Output:
} (5,5)
(10,10)
❑ const p1 = new Point(5, 5);
p1.diplay(); Point
const p2 = new Point(10, 10); 7.0710678118654755
p2.diplay();
console.log(Point.displayName);
console.log(Point.distance(p1, p2));
48
48
24
10/24/2024
❖ get prop() { /* … */ }
set name(newName) {
❖ set prop(value) { /* … */ } console.log("invoking set name()... newName=" + newName);
this._name = newName;
❑ ES6 computed property }
}
49
49
Inheritance
❑ class Animal {
constructor(name) { ❑ Console debug
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
speak() {
console.log(`${this.name} barks.`);
}
}
x = new Dog("Mitzie");
x.speak(); // Mitzie barks.
Output:
I am just an animal makes a noise.
Mitzie barks.
50
50
25
10/24/2024
Prototype
51
51
52
52
26
10/24/2024
Prototype in Inheritance
<<native code>>
❑ Class Person & Teacher are defined with their methods prototype
Person
anonym : object
❖ class Person { name: string
getName() { constructor: function getName(): function
return(this.name); toString(): function
}
setName(newname) {
this.name = newname;
Person : object
}
} prototype Teacher
constructor: class Person
__proto__
❖ class Teacher { getName(): function study(): function
teach() {
console.log('I am in class');
}
}
__proto__
hp : Teacher
name: ‘Hoang Pham’ creation
53
53
Functions
❑ Fundamental of JavaScript function
❑ Function as a type, in variable, passed by argument
❑ Advanced function use cases
❑ Function in OOP approach
❑ Rest parameters
JavaScript ❑ Callback
54
54
27
10/24/2024
JavaScript Functions
❑ To avoid repeating the same code all over places, ❑ Shorthand for declaring (arrow function)
use a function to wrap that code and reuse it ❖ let show = () => console.log('Anonymous function’);
❖ let compare = (a,b) => a > b ? 1:-1
❑ Declare a function
❖ function functionName(parameters) { ❑ Storing functions in variables
// function body
// ...
❖ Can treat functions like values of other types
} ❖ function add(a, b) {
return a + b;
❑ Calling a function }
55
55
56
56
28
10/24/2024
Object Function
57
57
❑ Function.prototype is defined with native methods, so available to all (object) functions in JavaScript
❑ call()
❖ .call(thisArg, arg1, arg2, ...);
❖ considered as static method of Function class
❖ thisArg: object to apply (can be null or obmit)
❖ arg1, arg2, ...: function arguments
❑ apply()
❖ .apply(thisArg, [args]);
❖ same as call() but arguments provided as an array
❑ bind()
❖ Returns a new function, when invoked, has its this sets to a specific value.
❖ Unlike the call() and apply() methods, the bind() method doesn’t immediately execute the function. It just returns a new
version of the function whose this sets to thisArg argument.
❖ let sum = add.bind(null)
❖ sum(3,6) // 9
58
58
29
10/24/2024
Rest Parameters
❑ ES6 provides a new kind of parameter so-called rest parameter that has a prefix of three dots (...)
❑ A rest parameter allows to represent an indefinite number of arguments as an array
❑ New add() function:
❖ function add(...args) {
let total = 0;
for (a of args) {
total += a;
}
return total;
}
❖ add(1, 2, 3, 4); // 10
❖ pars=[1,2,3,4,5,6,7,8,9]
❖ add.apply(null, pars) // 45
59
59
Function callback
❑ Asynchronous situation (common AJAX cases)
❑ Remember Array sort(compareFn()) ❖ function getUsers() { // get from DB server, asynch & take time
let users = [];
❖ function compareFn(propertyName) { setTimeout(() => { // stimulate delay 1 second at DB server
return function (a, b) { users = [
let x = a[propertyName], { username: 'john', email: 'john@test.com' },
y = b[propertyName]; { username: 'jane', email: 'jane@test.com' },
return (x > y ? 1:-1); ];
}; }, 1000);
} return users;
❖ products.sort(compareFn('name')); }
❖ products.sort(compareFn('price')); ❖ function findUser(username) {
const users = getUsers();
const user = users.find((user) => user.username === username);
return user;
❑ compareFn() is callback function }
Reason!!!
❖ console.log(findUser('john'));
❑ sort() accept compareFn() as an argument, so it’s
called high-order function ❑ Using callback to deal with asynchronous situation
function getUsers(callback) {
A synchronous callback is executed during the
❖
❑ setTimeout(() => {
execution of the high-order function that uses callback([
{ username: 'john', email: 'john@test.com’ },
the callback: The compare() is examples of { username: 'jane', email: 'jane@test.com’ },
]);
synchronous callbacks because it executes during }, 1000);
the execution of the sort() function. ❖
}
function findUser(username, callback) {
getUsers((users) => {
const user = users.find((user) => user.username ===
username);
callback(user);
});
}
❖ findUser('john', console.log);
60
60
30
10/24/2024
❑ download() function with error processing ❑ Popular in web service API invocation
function download(url, success, failure) {
setTimeout(() => { ❑ Banking service integration
console.log(`Downloading the picture from ${url} ...`);
!url ? failure(url) : success(url); // stimulate error
}, 1000); ❑ Authentication service access, etc…
}
download(
'',
(url) => console.log(`Processing the picture ${url}`),
(url) => console.log(`The '${url}' is not valid`)
);
61
61
JavaScript
62
62
31
10/24/2024
Promise Object
63
63
64
64
32
10/24/2024
Click
65
65
Promise Chaining
❑ Sometimes, we need to execute two or more ❑ Note that we can have multiple handlers for a
related asynchronous operations, where the next promise (multi then() method for the same Promise)
operation starts with the result from the previous ❖ let p = new Promise((resolve, reject) => {
one. setTimeout(() => {
resolve(10);
}, 3 * 100);
❖ getUser(), if success });
❖ then getUserService(), if success ❖ p.then((result) => {
console.log(result);
❖ then getUserServiceCost(), if success return result * 2;
})
❖ then invokeUserServiceAndPay ()
❖ p.then((result) => {
❑ Promise then() can return another promise object, console.log(result);
return result * 3;
depending on the fulfilled value })
❖ p.then((result) => {
❖ let p = new Promise((resolve, reject) => { console.log(result);
setTimeout(() => { return result * 4;
resolve(10); });
}, 3 * 100);
});
❖ p.then((result) => {
console.log(result);
return result * 2;
}).then((result) => {
console.log(result);
return result * 3;
}).then((result) => {
console.log(result);
return result * 4;
});
66
66
33
10/24/2024
67
67
JavaScript Promise.all()
68
68
34
10/24/2024
❑ Promise.race()
❖ Returns a new promise that fulfills or rejects as
soon as there is one promise that fulfills or
rejects
❑ Promise.allSettled()
❖ Returns a new promise that resolves after all
the input promises have settled, either resolved
or rejected
❑ Promise.any()
❖ Returns a single promise that resolves to a
value of the fulfilled promise
❖ Return a promise that is rejected with an
AggregateError if all rejected
69
69
async/await
70
70
35
10/24/2024
ES6 capabilities
JavaScript
71
71
❑ Language capabilities
❖ let and const ❖ Promises
❖ Arrow function ❖ Classes
❖ Modules
❖ Default function parameters
❖ Generators
❖ Rest parameters ❖ Symbols
❖ Spread operator ❖ Map and Set
❖ Destructuring ❖ WeakMap and WeakSet
❖ Template literals ❖ Proxy
❖ Reflect
❖ Object literal
❖ Async and Await
❖ For...of Loop ❖ Iterators
❖ Typed Arrays
source: https://www.w3schools.com/js/js_versions.asp
72
72
36
10/24/2024
❑ The let and const keywords are two of ❑ Arrow functions are a concise (ngắn gọn) way to
the most important additions to write functions in JavaScript
JavaScript in ES6 ❖ const myFunc = (param1, param2) => {
// code here
❑ To declare variables that are scoped to };
the block, statement, or expression in ❑ Always anonym function
which they are used
❖ let x = 5; ❑ Don’t have arguments object
let y = 10; ❖ function Fn(a) {
const z = 15; console.log(arguments)
❖ x = 20; }
z = 25; // Error: z is read-only ❖ Fn(10)
73
73
❑ Rest parameters allow to represent an ❑ The spread operator, which is denoted by three dots (...), is
indefinite number of function arguments as used to spread the values of an iterable object into multiple
an array elements
function sum(...args) {
It is commonly used to spread the
❖
return args.reduce((acc, cur) => acc + cur); ❑
} values of an array into multiple
❖ console.log(sum(1, 2, 3)); // 6 arguments of a function call
❖ const arr = [1, 2, 3];
console.log(...arr);
74
74
37
10/24/2024
75
75
❑ Template literals are string literals that allow ❑ Object literals are collections of key-value pairs,
embedded expressions which can be used to store data and access it in an
efficient manner.
❑ Can use template literals to create multi-line
strings and to use string interpolation features to ❑ Object literals are created using curly braces, and
create strings the key-value pairs are separated by commas
❑ Template literals are enclosed by the backtick (` `) ❑ Object literals can store function
character instead of double or single quotes ❖ const obj = {
key1: 'value1',
❖ const name = 'John';
key2: 'value2',
❖ const message = `Hello, ${name}!`; key3: 'value3',
❖ console.log(message); // Hello, John! calculateArea: (width, height) => {
return width * height;
}
};
76
76
38
10/24/2024
❑ Iterator is a powerful concept to loop through ❑ Loop to iterate keys in object with for…in
data, such as arrays and objects. ❖ const myObject = {
name: 'John',
❑ Iterator can be applied with iterable data (such as };
age: 30
arrays and objects) ❖ for (let key in myObject) {
console.log(myObject[key]);
❑ The most common iterator use case is the for…of }
loop to iterate through an array, or other
collection of data ❑ forEach() method is used to loop through an array,
❖ const myArray = [1,2,3,4,5]; object, or other collection
❖ for (let val of myArray) { ❖ const myArray = [1,2,3,4,5];
console.log(val); ❖ myArray.forEach((item) => console.log(item))
}
77
77
Iterator protocol:
return {value: counter,done: true};
❑ }
}
❖ has a next() method that returns an }
object with two properties: };
➢ done: a boolean value indicating whether ❑ let evenNumbers = new Sequence(2, 10, 2);
or not there are any more elements that for (const num of evenNumbers) console.log(num);
could be iterated upon.
❑ let oddNumbers = new Sequence(1, 10, 2);
➢ value: the current element. for (const num of oddNumbers) console.log(num);
❖ Last items in iterator: next() return object
{done: true: value: undefined}
78
78
39
10/24/2024
Symbols
❑ Case study: using string as status ❑ Symbol can be used for object keys
❖ const status = { ❖ Ambigiuos in using string as oject key
OPEN: 'Open', let me = {name:'Hoàng Phạm’,
IN_PROGRESS: 'In progress', office:'EdTech Centre'}
COMPLETED: 'Completed', for (key in me) console.log(me[key])
HOLD: 'On hold', me[name] // undefined
CANCELED: 'Canceled' me['name'] // Hoàng Phạm
};
❖ let task = new Task(statatus.OPEN); ❖ Using symbols as key
task.changeTo(status.COMPLETE)
const key1 = Symbol();
❑ Symbols const key2 = Symbol();
const myObject = {
❖ New primitive type provided in ES6 key1: 'Value 1',
key2: 'Value 2'
❖ let status = { };
OPEN: Symbol('Open'),
IN_PROGRESS: Symbol('In progress'),
COMPLETED: Symbol('Completed'),
HOLD: Symbol('On hold'),
CANCELED: Symbol('Canceled')
};
❖ task.setStatus(status.COMPLETED);
79
79
Generator
❑ How a function execution can pause and resume? ❑ Using generators to implement iterators
Generator is the solution: ❖ class Sequence {
❖ function* generate() { constructor(start=0,end=Infinity,interval=1) {
console.log('invoked 1st time’); this.start = start;
yield 1; this.end = end;
console.log('invoked 2nd time’); this.interval = interval;
yield 2; }
} * [Symbol.iterator]() {
for(let i=this.start; i<=this.end; i+=this.interval) {
❖ let gen = generate(); yield i;
}
❑ Return value function* is not a }
}
80
80
40