KEMBAR78
Handout 04. Javascript | PDF | Java Script | Computer Programming
0% found this document useful (0 votes)
8 views40 pages

Handout 04. Javascript

This document serves as a comprehensive guide to JavaScript, covering various sections from getting started to advanced topics like promises and error handling. It includes information on JavaScript's history, syntax, data types, and common scripting tasks for web programming. Additionally, it provides practical examples and IDE setup instructions for using JavaScript effectively.

Uploaded by

loductia12
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)
8 views40 pages

Handout 04. Javascript

This document serves as a comprehensive guide to JavaScript, covering various sections from getting started to advanced topics like promises and error handling. It includes information on JavaScript's history, syntax, data types, and common scripting tasks for web programming. Additionally, it provides practical examples and IDE setup instructions for using JavaScript effectively.

Uploaded by

loductia12
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/ 40

10/24/2024

JavaScript

Content

❑ Section 1. Getting started ❑ Section 9. Promises & Async/Await


❑ Section 2. Fundamentals ❑ Section 10. Iterators & Generators
❑ Section 3. Operators ❑ Section 11. Modules
❑ Section 4. Control flow Statements ❑ Section 12. Symbol
❑ Section 5. Functions
❑ Section 13. Collections
❑ Section 6. Objects & Prototypes
❑ Section 14. Error handling
❑ Section 7. Classes
❑ Section 8. Advanced Functions ❑ Section 15. JavaScript var, let, and const
❑ Section 16. Proxy & Reflection
❑ Section 17. JavaScript Runtime
❑ Section 18. Primitive Wrapper Types

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

Section 1. Getting started


❑ Market survey for client-side Web programming
❑ What is JavaScript, and its history
❑ JavaScript IDE installation
❑ Console Tab of Web Development Tools
❑ JavaScript Hello World
JavaScript

Market survey 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

Client-side for Web Programming

❑ HTML & CSS 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 for Web 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

❑ JavaScript is standard scripting language in Web browser


❑ Can be at server side also (Node.js)

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

Common scripting tasks in Web page

❑ 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 Information and Communication Technology
6

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.

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


School of Information and Communication Technology
7

JavaScript Quick View

❑ Use <script> tag to add Javascript code to a page <html>


<head>
<title>JavaScript Page</title>
❑ document.write displays text in the page </head>

❑ text to be displayed can include HTML tags <body>


<script type="text/javascript">
// silly code to demonstrate output
❑ JavaScript comments similar to C++/Java document.write("<p>Hello world!</p>");
document.write(" <p>How are <br/> " +
❖ // starts a single line comment " <i>you</i>?</p> ");
❖ /*…*/ enclose multi-line comments </script>
<p>Here is some static text as well.</p>
❑ JavaScript Can Change HTML Attribute Values </body>
</html>
<img id="myImage" src="pic_bulboff.gif" style="width:100px"> view page

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif’”> view page


Turn off the light</button>

❑ JavaScript Can Change HTML Styles (CSS)


<button onclick="document.getElementById('demo').style.fontSize='35px’”>
Click Me!</button>

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


School of Information and Communication Technology
8

4
10/24/2024

JavaScript IDE

❑ Browser developer tool (console) for(let i = 0; i < items.length; i++)


{
console.log(items[i]);
❑ Visual Studio Code: free by Microsoft }

JavaScript in Visual Studio Code:


https://code.visualstudio.com/docs/languages/javascript

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

❑ User and Workspace Settings


❖ https://code.visualstudio.com/docs/getstarted/settings#:~:text=Workspace%2
0settings.json%20location,inside%20the%20workspace%20configuration%20fi
le.
❖ User settings: apply globally to any opened instance of VS Code
❖ Workspace settings: stored inside workspace and only apply when the
workspace is opened.

❑ Create new Workspace:


❖ Menu File / Add folder to Workspace ➔ new “Untitled” Workspace created

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


School of Information and Communication Technology

10

10

5
10/24/2024

Live Server extension in VS Code

❑ Live server extension allows to launch a


development local server with the hot reload
feature for static pages.
❑ Install the Live Server extension:
❖ Click the Extensions.
❖ Search for the Live Server and select the Live Server
extension on the list.
❖ Click the Install button.
❑ Live Server settings: root directory & port
❖ User/Workspace setting, search “Live Server root”
❖ Click “Edit in setting.json”:
❖ {
"folders": [...],
"settings": {
"liveServer.settings.root": `...`
}
}

❑ To run static webpage with Live Server:


❖ Prepare webpage (html, css, js files)
❖ Locate html file in Code Explorer
❖ Mouse menu: Open in Live Server

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


School of Information and Communication Technology

11

11

HelloWorld application with JavaScript by VS Code

❑ Prepare working directory (D:/IT4409/JavaScript)


❑ Create Workspace in VS Code & add working folder
❑ HelloWorld js application
❖ <html>
<head>
<meta charset="UTF-8">
<title>JavaScript Workspace</title>
<script>console.log("Hello World")</script>
</head>
<body>
<h1>Hello World!!!</h1>
</body>
</html>

❖ Just open HTML file by browser


or “Open with Live Server” to run HelloWorld
❖ Open with Live Server auto reload file when changed
while open by browser does not
❑ Using external JS file: remember to set root directory
for Live Server

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


School of Information and Communication Technology

12

12

6
10/24/2024

Js Fundamentals
❑ Syntax
❑ Variables
❑ Data Types
❑ Array
❑ Operators
JavaScript ❑ Control Flow

13

13

JavaScript Syntax in brief

❑ Whitespace: Carriage return, Space, New Line, tab


❑ Statements
❖ A statement is concluded by a semicolon (;).
❖ Semicolon (;) is optional, but should use it to terminate a statement.

❑ Blocks: { }
❑ Identifiers: Case-sensitive. The message is different from the Message.
❑ Comments: // (inline) and /* … */ (block)

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


School of Information and Communication Technology

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);
}

❑ Undefined vs. undeclared variables


❖ Undefined variable:
console.log("message = " + message);
Output:
❖ Declared variable but not assigned ➔ undefined value message = undefined
let message;
console.log("message = " + message);
Output:
❖ Assign value to undeclared variable: message = Hello World
message = "Hello World";
console.log("message = " + message);

❑ JS does not accept undeclared variables,


but we can assign value to undeclared variables (implicit variables declaration with value)
❑ Data type is not specified when declaring variables, but when assign value

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


School of Information and Communication Technology

15

15

Data Types

❑ Primitive data types: ❑ The undefined type: default


❖ null, undefined, boolean, number, string let counter;
console.log(counter); // undefined
❖ symbol – available from ES2015
console.log(typeof counter); // undefined
❖ bigint – available from ES2020
❖ object - complex data type ❑ The object type
❖ Not OOP
❑ Js is a dynamically typed language: a variable isn’t
Similar to Java enum type
associated with a specific type

let emptyObject = {};
let counter = 120; // counter is a number let person = {
counter = false; // counter is now a boolean firstName: ‘John’,
lastName: ‘Doe’
counter = "foo"; // counter is now a string
};
❖ typeof operator: console.log(contact.firstName);
let counter = 120;
console.log(typeof(counter)); // "number" ❑ null, boolean, number, string: similar to Java
counter = false;
console.log(typeof(counter)); // "boolean"
❖ Numeric Separator: easy to interpret
const budget = 1000000000;
counter = "Hi";
const budget = 1_000_000_000; // the same with above
console.log(typeof(counter)); // "string“
❖ string
➢ accept ‘’ and “”: ‘hi’ and “hi” are the same
➢ ES6 introduced allow to define a string backtick (`)
let mesage = `"I'm good". She said";`

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


School of Information and Communication Technology

16

16

8
10/24/2024

Array

❑ JavaScript arrays ❑ Operations on arrays


❖ Similar to Java array type ❖ Adding an element to the end
❖ the size is dynamic and let seas = ['Black', 'Caribbean', 'Baltic'];
auto-growing seas.push('Red Sea');

❖ Array elements can be ❖ Adding an element to the beginning


different type seas.unshift('Red Sea’);
❖ Removing an element from the end
lastElement = seas.pop();
❑ Creating JavaScript arrays ❖ Removing an element from the beginning
let scores = new Array();
firstElement = seas.shift();
let scores = Array(10);
❖ Finding an index of an element
let scores = new Array(9,10,8,7,6);
index = seas.indexOf('North Sea');
let arrayName =
[element1, element2, element3, ...]; ❖ Check if a value is an array
let mountains = console.log(Array.isArray(seas)); // true
['Everest', 'Fuji', 'Nanga Parbat'];
❖ Sorting
❑ Array elements & size console.log(seas.sort()); // ['Baltic',
console.log(mountains[0]); // 'Everest’ 'Black', 'Caribbean']

console.log(mountains[1]); // 'Fuji’
console.log(mountains.length); // 3

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


School of Information and Communication Technology

17

17

Operators

❑ Arithmetic Operators: +, -, *, / ❑ Nullish coalescing operator


Accepts two values and returns the second value if the first
❑ Remainder Operator: % ❖
one is null or undefined
❑ Assignment Operators: =, +=, -=, etc… ❖ value1 ?? value2
❖ let result = value1;
❑ Unary Operators: +x, ++, -x, --, etc… If (result == null || result == undefined) {
result = value2;
❑ Comparison Operators: ==, !=, <, >, <=, >= }
❖ let result = (null || undefined) ?? 'OK';
❑ === equal value and equal type
❑ Exponentiation Operator: **
❑ Logical Operators: !, &&, || ❖ Math.pow(base, exponent)
❖ let result = Math.pow(n,i);
❑ Logical Assignment: ||=, &&=, ??= ❖ let result = n**i;
x ??= y;
❖ assigns y to x if x is null or undefined

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


School of Information and Communication Technology

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

if, else, switch and ?:

❑ if, if else, if else if ❑ switch case


❖ If (condition) statement; ❖ switch (expression) {
❖ if (age >= 18) { case value1:
console.log('You can sign up’); statement1;
} break;
case value2:
❖ if (condition1) { statement2;
// ... break;
} else if (condition2) { case value3:
// ... statement3;
} else { break;
//... default:
} statement;
}
❑ Ternary Operator
❖ age >= 16 ? (message = 'You can drive.') : (message = 'You
cannot drive.’);
console.log(message);
❖ let speed = 90;
let message =
speed >= 120 ?
'Too Fast' : speed >= 80 ?
'Fast' : 'OK’;
console.log(message); // Fast

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


School of Information and Communication Technology

20

20

10
10/24/2024

Loop flow control

❑ while ❑ while with break


❖ while (expression) { ❖ let i = 0;
// statement while (i < 5) {
} i++;
console.log(i);
❑ do while if (i == 3) {
break;
❖ do { }
statement; }
} while(expression);

❑ for ❑ for with break


❖ for (initializer; condition; iterator) { ❖ let j = 1;
// statements for (;;) {
} if (j > 10) {
break;
}
❖ Infinitive loop: console.log(j);
j += 2;
for ( ; ; ) { }
// statements
}

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


School of Information and Communication Technology

21

21

More about “break” and “continue”

❑ label statement ❖ label is optional:


Output:
❖ for (let i = 1; i <= 3; i++) {
❖ label: statement; for (let j = 1; j <= 3; j++) { 1 1
❖ the label can be any valid identifier if (i + j == 4) {
break;
1 2
2 1
❖ The statement can be a loop or switch }
console.log(i, j);
❖ outer: for (let i = 0; i < 5; i++) { }
console.log(i); }
}
❖ Once define a label, we can reference it in the break or ❑ continue: terminates the current loop iteration and
continue statement. immediately continues to the next iteration
❑ break: terminates a loop such as for, do...while, a ❖ continue [label]; Output:
switch, or a label statement ❖ outer: for (let i = 1; i < 4; i++) {
for (let j = 1; j < 4; j++) {
1 1
3 1
❖ break [label]; if (i + j == 3) continue outer; 3 2
console.log(i, j);
❖ to break a statement identified by label } 3 3
}
❖ outer: for (let i = 1; i <= 3; i++) { Output:
for (let j = 1; j <= 3; j++) { 1 1 ❖ let i = 0; Output:
if (i + j == 4) { while (i < 10) { 1
break outer;
1 2 i++;
} if (i % 2 === 0) { 3
console.log(i, j); continue; 5
} } 7
} console.log(i);
}
9

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


School of Information and Communication Technology

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

❖ let board = [1, 2, 3, 4, 5, 6, 7, 8, 9];


let s = ‘’;
for (let i = 0, j = 1; i < board.length; i++, j++) {
s += board[i] + ' ‘;
if (j % 3 == 0) {
console.log(s); Output:
s = ‘’; 1 2 3
}
}
4 5 6
7 8 9

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


School of Information and Communication Technology

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.

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


School of Information and Communication Technology

25

Objects definition and calculation

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


School of Information and Communication Technology

26

13
10/24/2024

Object references

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


School of Information and Communication Technology

27

Garbage collection

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


School of Information and Communication Technology

28

14
10/24/2024

Garbage collection (2)

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


School of Information and Communication Technology

29

Garbage collection (3)

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


School of Information and Communication Technology

30

15
10/24/2024

Object property: prototype

❑ All JavaScript object has default prototype property,


refer by __proto__
❖ let me = {name: 'Hoang Pham', office: 'EdTech Centre’}
❖ typeof(me.__proto__) // 'object’
❖ me.toString() // ‘[object Object]’

❑ Not to access as defined properties, __proto__ to hold


the reference to ‘object’ which has several methods
❑ When invoke a method or access to a property,
if not find, JavaScript engine will look for in __proto__
❑ Build-in objects: each has different prototype
❖ String
❖ Array
❖ Math
❖ Function
❖ Number
❖ v.v..

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


School of Information and Communication Technology

31

31

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)

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


School of Information and Communication Technology
32

32

16
10/24/2024

String example: Palindromes

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

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


School of Information and Communication Technology
33

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

the built-in Math object contains functions


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

view page
Math.random function returns a real
number in [0..1)

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


School of Information and Communication Technology
35

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

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


School of Information and Communication Technology
36

36

18
10/24/2024

Array Object

❑ Arrays store a sequence of items, accessible via an


index
❑ Array can be used as an object
➢ items = [1,2,3,4,5,6,7,8,9,10];
typeof(items) // object
for (pro in items) console.log(pro) // 1 2 3..
➢ item.__proto__

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


School of Information and Communication Technology
37

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

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


School of Information and Communication Technology
38

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 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]

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


School of Information and Communication Technology
39

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)

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


School of Information and Communication Technology
40

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

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


School of Information and Communication Technology
42

42

21
10/24/2024

Document Object

Internet Explorer, Firefox, Opera, etc. allow you to <html>


access information about an HTML document using <!–- CS443 js13.html 2.10.2012 -->
<head>
the document object <title>Documentation page</title>
</head>
<body>
<table width="100%">
document.write(…) <tr>
<td><i>
method that displays text in the page <script type="text/javascript">
document.write(document.URL);
</script>
</i></td>
document.URL <td style="text-align: right;"><i>
<script type="text/javascript">
property that gives the location of the document.write(document.lastModified);
</script>
HTML document </i></td>
</tr>
</table>
</body>
document.lastModified </html>

property that gives the date & time the


view page

view page
HTML document was last changed

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


School of Information and Communication Technology
43

43

JS Object Oriented Programming


❑ Overview OOP in JavaScript
❑ Class definition & Object creation
❑ Object by shorthand
❑ Public, private, static
❑ Getters, setters and computed property
JavaScript ❑ Inheritance
❑ Prototype

44

44

22
10/24/2024

JavaScript OOP Overview

❑ Before ES6, JavaScript had no concept of classes, meaning no OOP


❑ Pseudo OOP:
❖ function Person(name) {
this.name = name;
} source: https://www.w3schools.com/js/default.asp

Person.prototype.getName = function () {
return this.name;
};

var john = new Person("John Doe");


console.log(john.getName());

❑ ES6 OOP
❖ class declaration
❖ class Person {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}

source: https://www.w3schools.com/js/js_versions.asp

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


School of Information and Communication Technology

45

45

JavaScript Class & Object

❑ Class declaration & object creation


❖ class Person {
constructor(name) {
console.log("starting constructor... name=" + name);
this.name = name;
}
getName() {
console.log("invoking getName()...");
return this.name;
} Output:
setName(newName) {
console.log("invoking setName()... newName=" + newName); starting constructor... name=John Doe
this.name = newName; invoking getName()...
} John Doe
} invoking setName()... newName=Elon Musk
invoking getName()...
let john = new Person("John Doe");
Elon Musk
console.log(john.getName());
john.setName("Elon Musk");
console.log(john.getName());

❑ No need to define class fields (just as variables)


❑ But!!! get() should be invoked after set() (remember JS does not accept undeclared variables)
❑ ➔ constructor() (JS class has only one constructor) takes the responsibility to define ALL class fields with
value (so type)

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


School of Information and Communication Technology

46

46

23
10/24/2024

Object method shorthand

❑ Object literal syntax Output:


❖ let john = {
name: "John Doe", invoking getName()...
getName() { John Doe
console.log("invoking getName()..."); invoking setName()... newName=Elon Musk
return this.name; invoking getName()...
}, Elon Musk
setName(newName) {
console.log("invoking setName()... newName=" + newName);
this.name = newName;
}
}

console.log(john.getName());
john.setName("Elon Musk");
console.log(john.getName());

❖ let me = {name : 'Hoang', office : 'EdTech' }

❑ No constructor ➔ need to define class fields


❑ Fields, methods are listed with comma (,) separated

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


School of Information and Communication Technology

47

47

Public, Private & Static

❑ 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));

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


School of Information and Communication Technology

48

48

24
10/24/2024

Getters and Setters

❑ OOP public/private methodology ❑ class Person {


constructor(name) {
❖ Private property console.log("starting constructor... name=" + name);
this._name = name; // no more ‘name’ field but ‘_name’
❖ Public access: getter & setter methods }

❑ ES6 provides a specific syntax for defining getter get name() {


console.log("invoking get name()...");
and setter using the get and set keywords }
return this._name;

❖ get prop() { /* … */ }
set name(newName) {
❖ set prop(value) { /* … */ } console.log("invoking set name()... newName=" + newName);
this._name = newName;
❑ ES6 computed property }
}

❖ parameterize the property name ❑ let john = new Person("John Doe");


❖ get/set [prop]() { /* … */ } console.log(john.name);
❖ const addr = "address"; john.name = "Elon Musk";
class Person { console.log(john.name);
get [addr]() {
return "EdTech / SoICT / HUST";
} Output:
set [addr](newAddr) { starting constructor... name=John Doe
console.log(`invoking set addr()... newAddr=${newAddr}`); invoking get name()...
} John Doe
}
invoking set name()... newName=Elon Musk
❖ let me = new Person("Hoang Pham"); invoking get name()...
console.log(me.address); Elon Musk
me.address = "Some where in the HUST";
console.log(me.address);

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


School of Information and Communication Technology

49

49

Inheritance

❑ class Animal {
constructor(name) { ❑ Console debug
this.name = name;
}

speak() {
console.log(`${this.name} makes a noise.`);
}
}

❑ class Dog extends Animal {


constructor(name) {
super(name); // call the super class constructor
}

speak() {
console.log(`${this.name} barks.`);
}
}

❑ let x = new Animal("I am just an animal");


x.speak();

x = new Dog("Mitzie");
x.speak(); // Mitzie barks.

Output:
I am just an animal makes a noise.
Mitzie barks.

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


School of Information and Communication Technology

50

50

25
10/24/2024

Prototype

❑ In JavaScript, prototype is the mechanism to implement null


OOP prototype chain

❑ Every class has its own property (field) called a __proto__


prototype (object type)
anonym : object
❖ typeof(Person.prototype) ➔ ‘object’
❖ typeof(Object.prototype) ➔ ‘object’ constructor: function
toString(): function
❖ typeof(Object) ➔ ‘function’
<<native code>>
❑ When access to an object property (or method), it __proto__
returns the value of the name property as expected.
Person : object
❑ If the property doesn’t exist in an object, JS engine will constructor: class Person
search in the prototype of the object. getName(): function

❑ If cannot find the property in the object’s prototype, it’ll


search in the prototype’s prototype until the end of the __proto__
prototype chain. Teacher : object
constructor: class Teacher
teach(): function

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


School of Information and Communication Technology

51

51

Prototype in Class definition/Object creation

❑ By default, the JS engine provides a built-in Object() function


and an anonym object referenced by Object().prototype <<native code>>
Person
❑ When declare a class, JS engine create an holder object to hold Object() prototype
the contructor and methods definition of the class. As class has name: string
getName(): function
default perperty [[prototype]], the holder object has __proto__ __proto__
field to refer to anonym object
<<native code>>
❑ An object created from class also has __proto__ to refer to holder
object. By this __proto__ field, object can access to the “its anonym : object

design” to change constructor: function Person : object


toString(): function
❖ class Person { constructor: class Person
constructor(name) { __proto__ getName(): function
this.name = name; setName(): function
} null
} __proto__

❖ let hp = new Person(‘Hoàng Phạm’)


❖ hp.____proto__.setName = function(newName) { __proto__
this.name = newname;
}
❖ hp.setName(‘new Hoàng Phạm’) hp : Person creation
❖ hp.name ➔ ‘new Hoàng Phạm’
name: ‘Hoang Pham’

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


School of Information and Communication Technology

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');
}
}

❑ Setting the inheritance by prototype Teacher : object

❖ Teacher.prototype.__proto__ = Person.prototype constructor: class Teacher


__proto__ study(): function
❖ let hp = new Teacher()
❖ hp.teach() ➔ I am in class
❖ hp.setName(‘Hoang Pham’)
❖ hp.getName() ➔ ‘Hoang Pham’

__proto__

hp : Teacher
name: ‘Hoang Pham’ creation

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


School of Information and Communication Technology

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 }

❖ functionName(arguments); let sum = add;


let result = sum(10,20);
❑ Returning a value
❖ return expression;
❖ JavaScript functions implicitly return undefined unless
explicitly specify a return value
❖ function say(message) {
console.log(message); Output:
} Hello
Result: undefined
let result = say('Hello’);
console.log('Result:', result);

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


School of Information and Communication Technology

55

55

Advanced function use cases

Function as function’s parameter Function as return value from another function


❑ Remember Array.sort() ❑ Array of object with several
❖ let numbers = [5, 10, 9, 12, 40, 25] properties (name & price)
❖ number.sort() // [10, 12, 25, 40, 5, 9] ❖ let products = [
❖ Because sort string by default {name: 'iPhone', price: 900},
{name: 'Samsung Galaxy', price: 850},
{name: 'Sony Xperia', price: 700}
❑ Custom sort() ];
❖ sort(compareFn()) method accepts a function ❖ console.table(products)
that compares two elements of the array
❑ How to apply sort(compareFn())
❖ let compareFn = (a,b) => a>b ? 1:-1 with property (name, price)?
❖ number.sort(compareFn) // [5,9,10,12,25,40] ❖ function compareFn(propertyName) {
return function (a, b) {
let x = a[propertyName],
y = b[propertyName];
if (x > y) {
return 1;
} else if (x < y) {
return -1;
} else {
return 0;
}
};
}
❖ console.table(products.sort(compareFn('name')));
❖ console.table(products.sort(compareFn('price')));

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


School of Information and Communication Technology

56

56

28
10/24/2024

Object Function

❑ All JavaScript functions are objects, instances of Function type


❑ Because functions are Function object, they have 2 default
properties: length and prototype
❖ function add(x, y) {
return x + y;
}
❖ console.log(add.length)
❖ Console.log(add.prototype)

❑ As being object, add can invoke Function methods such as call():


❖ add.call(null, 3, 5) // 8
❖ ddd.toString() // function add(x,y) { return x+y }’
<<native code>>
❑ Even we can defile new method for Function Function creation
❖ add.__proto__.newCall = function() { length add : Function
console.log('new Function method') prototype __proto__
} call()
❖ add.newCall() // new Function method apply()
❖ abc = function() { bind()
console.log('abc function’) ...
} abc : Function
prototype
❖ abc() // 'abc function’
__proto__
❖ abc.newCall() // new Function method
anonym : Function
newCall(): function
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

57

57

Function call(), apply() and bind()

❑ 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

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


School of Information and Communication Technology

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

❑ Combine normal & rest parameters


❖ function add(parity,...arg) {
let total = 0;
for (a of arg) {
if (parity=='odd' && a%2==1) total += a;
if (parity=='even' && a%2==0) total += a;
}
return total;
}
❖ add('odd',1,2,3,4,5,6,7) // 16
❖ add('even',1,2,3,4,5,6,7) // 12

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


School of Information and Communication Technology

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);

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


School of Information and Communication Technology

60

60

30
10/24/2024

Handling callback function errors/result

❑ 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`)
);

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


School of Information and Communication Technology

61

61

Promises & Async/Await


❑ Promise object for asynchronous operation
❑ Promise Chaining
❑ Promise static methods for promise chain
❑ async/await

JavaScript

62

62

31
10/24/2024

Promise Object

❑ Promise is a native object that encapsulates the ❑ Consuming a Promise: then()


result of an asynchronous operation ❖ To get the value of a promise when it’s fulfilled
❖ let success = true; // stimulate error
❖ function getUsers() {
return new Promise((resolve, reject) => {
setTimeout(() => {
❑ State of promise object if (success) {
resolve([
❖ Pending: asynch operation is in progress { username: 'john', email: 'john@test.com' },
{ username: 'jane', email: 'jane@test.com' },
❖ Fulfilled: asynch operation was completed successfully ]);
} else {
❖ Rejected: asynchronous operation failed reject('Failed to the user list');
}
❑ Creating a promise }, 1000);
}); 1 second
❖ promise = new Promise((resolve, reject) => { }
// perform asynch operation latter
// ... ❖ function onFulfilled(users) {
console.log(users);
// return the state }
if (success) { ❖ function onRejected(error) {
resolve(value); console.log(error);
} else { }
reject(error);
❖ let promise = getUsers();
}
promise.then(onFulfilled, onRejected);
});
❖ constructor accepts a callback function (the executor) that ❖ success = false; // stimulate error
performs an asynchronous operation
❖ let promise = getUsers();
❖ executor accepts 2 callback functions: resolve() & reject() promise.then(onFulfilled, onRejected);

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


School of Information and Communication Technology

63

63

Promise Object (cont.)

❑ Consuming a Promise: catch() ❑ Consuming a Promise: finally()


❖ to get the error only when the state of the promise is ❖ Sometime need execute the same piece of code whether
rejected the promise is fulfilled or rejected
❖ let success = false; // stimulate error ❖ Code redundance: render()
❖ function getUsers() { ❖ const render = () => {
return new Promise((resolve, reject) => { //...
... // same as previous example };
});
} ❖ getUsers()
.then((users) => {
❖ let p = getUsers(); console.log(users);
❖ p.catch((error) => { render();
console.log(error); })
}); .catch((error) => {
console.log(error);
render();
});

❖ Apply finally() to avoid code redundance


❖ getUsers()
.then((users) => {
console.log(users);
})
.catch((error) => {
console.log(error);
})
.finally(() => {
render();
});

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


School of Information and Communication Technology

64

64

32
10/24/2024

Typical Promise sample with AJAX

Click

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


School of Information and Communication Technology

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;
});

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


School of Information and Communication Technology

66

66

33
10/24/2024

Promise Chaining (cont.)

❑ Promise chaining syntax ❖ function getServices(user) {


return new Promise((resolve, reject) => {
❖ Passing the result between steps: console.log(`Get the services of ${user.username} from the API.`);
setTimeout(() => {
step1() resolve(['Email', 'VPN', 'CDN']);
.then(result => step2(result)) }, 3 * 1000);
.then(result => step3(result)) });
... }
❖ function getServiceCost(services) {
❖ No need to pass the result between steps: return new Promise((resolve, reject) => {
step1() console.log(`Calculate the service cost of ${services}.`);
setTimeout(() => {
.then(step2) resolve(services.length * 100);
.then(step3) }, 2 * 1000);
... });
}
❑ Example ❖ getUser(100)
❖ function getUser(userId) { .then(getServices)
return new Promise((resolve, reject) => { .then(getServiceCost)
console.log('Get the user from the database.'); .then(console.log);
setTimeout(() => {
resolve({
userId: userId,
username: 'admin'
});
}, 1000);
})
}

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


School of Information and Communication Technology

67

67

JavaScript Promise.all()

❑ Static method Promise.all()


❑ Returns a single promise that resolves when all the input
promises have been resolved
❑ If one of the input promises is rejected, immediately returns a
promise that is rejected with an error of the first rejected
promise
❖ let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The first promise has resolved');
resolve(10);
}, 1 * 1000);
});
❖ let p2 = new Promise((resolve, reject) => {
...
});
❖ let p2 = new Promise((resolve, reject) => {
...
});
❖ Promise.all([p1, p2, p3]).then((results) => {
const total = results.reduce((p, c) => p + c);
console.log(`Results: ${results}`);
console.log(`Total: ${total}`);
});

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


School of Information and Communication Technology

68

68

34
10/24/2024

Other static methods

❑ 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

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


School of Information and Communication Technology

69

69

async/await

❑ Introduced in ES2017 ❑ Rewrite the sample


async function getUser(userId) {
To write asynchronous code that looks more

❑ console.log('Get user from the database.');
like synchronous code, so more readable. ❖
return {'userId':userId, 'userName': 'Hoàng Phạm'}}
async function getServices(user) {
console.log(`Get the services of ${user.userName} from the API.`);
❑ async keyword allows to define a function return(['Email', 'VPN', 'CDN']);
that handles asynchronous operations }
❖ async function getServiceCost(services) {
❑ Asynchronous functions execute console.log(`Calculate service costs of ${services}.`);
return (services.length * 100);
asynchronously (via the event loop) and }

always returns a Promise ❖ async function showServiceCost() {


let user = await getUser(100);
❖ async function sayHi() { let services = await getServices(user);
return 'Hi'; let cost = await getServiceCost(services);
} console.log(`The service cost is ${cost}`);
}
❖ sayHi().then(console.log);
❖ showServiceCost();

❑ await keyword to wait for a Promise to settle


either in a resolved or rejected state.
❖ async function display() {
let result = await sayHi();
console.log(result);
}

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


School of Information and Communication Technology

70

70

35
10/24/2024

ES6 capabilities

JavaScript

71

71

JavaScript ES6 https://playcode.io/javascript/es6

❑ JavaScript ES6 (ECMAScript 6) is the latest (main) version of


the JavaScript language
❖ Easier to write and understand JavaScript code.
❖ Provides new features and syntax changes that make JavaScript more source: https://www.w3schools.com/js/default.asp
powerful and expressive.
❖ Widely supported by modern browsers.

❑ 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

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


School of Information and Communication Technology

72

72

36
10/24/2024

let, const and Arrow function

❑ 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)

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


School of Information and Communication Technology

73

73

Rest and Spread

❑ 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);

❑ Can also be used to spread the


values of an object into a new object
❖ const obj = {
a: 1,
b: 2,
c: 3,
};
❖ const newObj = {
...obj,
a: 4,
};
❖ console.log(newObj);

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


School of Information and Communication Technology

74

74

37
10/24/2024

Default function parameter’s value & Destructuring

❑ To set default values for function parameters ❑ Destructuring allows to


quickly extract data
❑ Allow for more flexibility in function calls &
from objects
more control over the arguments passed into const person = {
a function

name: 'John',
❖ function getMessage(message, name = 'World') { age: 30
console.log(message + ', ' + name); };
} ❖ const {name, age} = person;
❖ getMessage('Hello'); // 'Hello, World'
❖ getMessage('Hello', 'John'); // 'Hello, John' ❑ Can be applied to more
complex objects & arrays
❖ const people = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 35 },
];
❖ const [john, jane, bob]
= people;

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


School of Information and Communication Technology

75

75

Template literals & Object literal

❑ 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;
}
};

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


School of Information and Communication Technology

76

76

38
10/24/2024

Iterators & new loops

❑ 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))
}

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


School of Information and Communication Technology

77

77

Create iterable objects

❑ JavaScript provide native code of ❑ class Sequence {


constructor(start=0,end=Infinity,interval=1) {
iterable for arrays and objects, so this.start = start;
this.end = end;
can apply iterator (for…of, for…in, this.interval = interval;
forEach()) }
[Symbol.iterator]() {
let counter = 0;
❑ An object is iterable when it let nextIndex = this.start;
return {
contains a method called next: () => {
[Symbol.iterator]() that takes no if (nextIndex <= this.end) {
let result = {value:nextIndex,done:false}
argument and returns an object that nextIndex += this.interval;
counter++;
conforms to the iterator protocol. }
return result;

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}

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


School of Information and Communication Technology

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);

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


School of Information and Communication Technology

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 }
}

function but generator object


❖ let oddNumbers =
❑ next() method new Sequence(1, 10, 2);

for (const num of oddNumbers) {


❖ Execute the function’s body ❖
console.log(num);
❖ Paused by yield }

❖ Returned value is by yield:


{value: 1, done: false}
❖ Resume when invoking next time

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


School of Information and Communication Technology

80

80

40

You might also like