0% found this document useful (0 votes)
3 views108 pages

JavaScript Basics for Web Development

Chapter 3 provides an introduction to JavaScript, detailing its history, usage in HTML documents, and basic features. It explains how JavaScript is an object-oriented, interpreted language supported by all major browsers and outlines the structure of JavaScript code, including variables, operators, and data types. The chapter also covers how to embed JavaScript in HTML, the execution process, and various output methods.

Uploaded by

nghib2303833
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)
3 views108 pages

JavaScript Basics for Web Development

Chapter 3 provides an introduction to JavaScript, detailing its history, usage in HTML documents, and basic features. It explains how JavaScript is an object-oriented, interpreted language supported by all major browsers and outlines the structure of JavaScript code, including variables, operators, and data types. The chapter also covers how to embed JavaScript in HTML, the execution process, and various output methods.

Uploaded by

nghib2303833
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

Chapter 3

JavaScript

College of Information and Communication Technology


Can Tho University
Dr. Trieu Thanh Ngoan

ĐẠI HỌC CẦN THƠ


CTU
1 [Link]
Cộng đồng – Toàn diện – Ưu việt
Faculty of Computer Network and Communication
Content
1. Introduction
2. Using JavaScript in an HTML documents
3. JS language basics
4. JS functions
5. DOM
6. OOP in JS

ĐẠI HỌC CẦN THƠ


CTU
2 [Link] 2
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
Content
1. Introduction
2. Using JavaScript in an HTML documents
3. JS language basics
4. JS functions
5. DOM
6. OOP in JS

ĐẠI HỌC CẦN THƠ


CTU
3 [Link] 3
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Introduction to JS

What is JavaScript?
• Javascript is a programming language (no relation to Java, it is named just for
marketing reason 😀)

• Currently is the only programming language for browsers


• It's supported by all popular browsers: Firefox, Chrome, Opera, Safari,
etc.
• JavaScript is used by billions of websites to create functions, check
data, exchange information with web servers, etc.
• JavaScript is an object-oriented, interpreted programming language that
is executed by the browser on the client side.

ĐẠI HỌC CẦN THƠ


CTU
4 [Link] 4
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Introduction to JS

What is JavaScript?
History:
• Originally developed by Brendan Eich at Netscape (named
LiveScript at that time)
• Became a joint venture of Netscape and Sun in 1995 (renamed
JavaScript)
• Now standardized by the ECMA (ECMA-262, also ISO 16262)

ECMA (European Computer Manufacturers Association) is an industry association


dedicated to the standardization of information and communication systems
ĐẠI HỌC CẦN THƠ
CTU
5 [Link] 5
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Introduction to JS

What is JavaScript?
ECMAScript (ES): a standard for scripting languages
JavaScript: a programming language based on ECMAScript (the most
popular implementation of ES)

ĐẠI HỌC CẦN THƠ


CTU
6 [Link] 6
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Introduction to JS

Why JavaScript?

+ produces

Describes the Describes the A web page... that doesn't


content and appearance and do anything, except:
structure of the page style of the page • Shows the information
• Links to other webpages

If we want dynamic, more friendly and interactive webpages (automation,


animation, interactivity, etc.)

JavaScript comes to help!


ĐẠI HỌC CẦN THƠ
CTU
7 [Link] 7
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Introduction to JS

What JS Can Do?


User interaction through form are easy
Document Object Model (DOM) makes it possible to create dynamic
HTML with JS:
• can change the HTML page content
• can show/hide HTML page elements
• can change the HTML element’s attributes
• etc.
And much more features that we can do with event-driven computation…

ĐẠI HỌC CẦN THƠ


CTU
8 [Link] 8
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Introduction to JS

Basic Features of JS
An interpreter language (no compilation by developers, it is compiled and executed
on-the-fly by browser)

Dynamic typed (no need to declare variables, auto type-casting)

Supports the OOP approach (but lack of some basic features of OOP such as
polymorphism)

ĐẠI HỌC CẦN THƠ


CTU
9 [Link] 9
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
Content
1. Introduction
2. Using JavaScript in an HTML documents
3. JS language basics
4. JS functions
5. DOM
6. OOP in JS

ĐẠI HỌC CẦN THƠ


CTU
10 [Link] 10
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Using JS in HTML Documents

Internal JS Code
JS code can be embedded directly in an HTML page using <script> tag:
<script>
... JavaScript code ...
</script>

The may be a number of scripts in an HTML page


Scripts can be placed in the <head> or in the <body> section

vNote: Placing scripts at the bottom of the <body> element improves the
display speed, because script compilation slows down the display

ĐẠI HỌC CẦN THƠ


CTU
11 [Link] 11
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Using JS in HTML Documents

External JS Code
JS script (code) can also be placed in external files and linked to HTML
pages
JS script files have the extension .js
To link a JS script, use the <script> tag with the src attribute:
<script src="<script ULR>"></script>
External JS script advantages:
• Separate JS code and HTML code (easy to read and maintain)
• JS code can be reused/shared in HTML pages
• Cached JS files can speed-up page load, and much more…

Recommended!
ĐẠI HỌC CẦN THƠ
CTU
12 [Link] 12
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Using JS in HTML Documents

External JS Code
External scripts can be referenced with a full URL (placed in other sites or the
same site) or with a relative path (placed in the same site)
Example:
<script src="scripts/[Link]"></script>
<script src="[Link]

vNotes:
• External JS scripts cannot contain <script> tags
• The <script> tag can be placed anywhere in the HTML page
• An HTML page can use multiple script files: use multiple <script>
tags to link to multiple script files
ĐẠI HỌC CẦN THƠ
CTU
13 [Link] 13
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Using JS in HTML Documents

How Does JS Code Get Loaded?


If a browser receive an HTML page with a reference to a JS file:
1) It will make a request to the web server for the script file
2) After receiving the script files, it will execute the script file

JS script execution:
There is no main function as other programming languages
⇒ The script code is executed from the top to the bottom
JS functions in the script file are only executed when called

ĐẠI HỌC CẦN THƠ


CTU
14 [Link] 14
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Using JS in HTML Documents

Output of JS
JS can display data in different ways:
• Writing into an HTML element, using innerHTML property
• Writing into HTML page, using [Link]()
(Note: Using [Link]() after an HTML document is loaded,
will delete all existing HTML)
• Writing into an alert box, using [Link]()
• Output to browser console, using [Link]()
(usually used for debugging purpose)

ĐẠI HỌC CẦN THƠ


CTU
15 [Link] 15
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Using JS in HTML Documents

Output of JS
Writing to an HTML element:
<!DOCTYPE html>
<html>
<body>
<h1>Today is: <span id="curdate"></span></h1>
<p>5 + 6 = <span id="calc"></span></p>
<script>
var d = (new Date()).toString().substring(0, 15);
[Link]("curdate").innerHTML = d;
[Link]("calc").innerHTML = 5 + 6;
</script>
</body>
</html>

ĐẠI HỌC CẦN THƠ


CTU
16 [Link] 16
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Using JS in HTML Documents

Output of JS
Writing into an alert box:
<!DOCTYPE html>
<html>
<body>
<h2>JS Output</h2>
<button onclick="alert('Hello!')">Click me to say Hello</button>
</body>
</html>

ĐẠI HỌC CẦN THƠ


CTU
17 [Link] 17
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Using JS in HTML Documents

Output of JS
Output to browser console:
<!DOCTYPE html>
<html>
<body>
<h2>JS to console</h2>
<script>
[Link]('Hello, world!');
</script>
</body>
</html>

ĐẠI HỌC CẦN THƠ


CTU
18 [Link] 18
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Using JS in HTML Documents

Output of JS
Output to browser console (cont.):
for
debugging

1. Right click

3. Choose Console

2. Click
Inspect

ĐẠI HỌC CẦN THƠ


CTU
19 [Link] 19
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
Content
1. Introduction
2. Using JavaScript in an HTML documents
3. JS language basics
4. JS functions
5. DOM
6. OOP in JS

ĐẠI HỌC CẦN THƠ


CTU
20 [Link] 20
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Statements
• Script/Program = { set of instructions/statements}
• A statement is composed of: values (constant/literals or variable), operators,
expressions, keywords, and comments
• A statement ends with a semicolon ;
• Multiple while-space are ignored (so we can add as much as white-space for
readability)
• A statement can be broken into multiple lines
• A set of statements can be grouped in code block, using {…}

ĐẠI HỌC CẦN THƠ


CTU
21 [Link] 21
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Comments
For code readability and maintenance
Will be ignored by JS (doesn’t interpret and execute)
Single line comments:
• Start with //
• … to the end of line
Multiline comments:
• Start with /*
• End with */
Good practice to use comments as much as possible

ĐẠI HỌC CẦN THƠ


CTU
22 [Link] 22
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Variables

Declaration: var/let/const <var_name> [ = <expression>];


Example: var/let name = 'Jerry', age = 40;
Datatype is not necessary in the variable declaration
(however, JS does has datatypes: number, boolean, string, object, function,
undefined, Array, Object, Date)
JS variables can also be used without declaration
Variable naming rules (same as identifier naming rules):
• Names can contain letters, digits, underscores, and dollar signs
• Names must begin with a letter, $ and _
• Names are case sensitive
ĐẠI HỌC CẦN THƠ
CTU
23 [Link] 23
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Variables
Declaring a variable without assigning value: the variable will have the
value undefined
var age; // ⇒ age = undefined
Re-declaring a variable doesn’t erase its value
var myAge = 40;
var myAge; // ⇒ age still = 40
Get the datatype of a variable: use the typeof operator
Example: typeof myAge returns a string “number”
We can declare multiple variables in one statement (using comma to
separate variable names)

ĐẠI HỌC CẦN THƠ


CTU
24 [Link] 24
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Variables
Hoisting is moving all declarations to the top of the current scope
When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you cannot use const
5. Never use var if you can use let or const.

ĐẠI HỌC CẦN THƠ


CTU
25 [Link] 25
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Operators

Assignment

Arithmetic
ĐẠI HỌC CẦN THƠ
CTU
26 [Link] 26
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Operators

Logical

String

JS also provides bitwise operators such as &


Comparison (AND), | (OR), ~ (NOT)
ĐẠI HỌC CẦN THƠ
CTU
27 [Link] 27
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Datatypes
JS variables don’t have types, but the values do
Primitive datatypes:
• Boolean: true or false
• Number: everything is double (no integers)
• String: in 'single' or "double" quotes
• Null: null, a value meaning “this has no value” (null is an object)
• Undefined: undefined, i.e. “not assigned”
Object types:
• Array, Date, Object, ...
null == undefined: true
null === undefined: false
ĐẠI HỌC CẦN THƠ
CTU
28 [Link] 28
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Number
All numbers in JS are real numbers, no integer
Operators are like C/C++ or Java
Precedence like C/C++ or Java
Some special values:
NaN == NaN: false
NaN (not-a-number) NaN != NaN: true
+Infinity
-Infinity
There is a Math class, which provide basic math functions (such as
[Link](), [Link](), etc.)

ĐẠI HỌC CẦN THƠ


CTU
29 [Link] 29
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

String
Object type
Can be defined with single quote (preferred) or double quote
Immutable
No char type: letters are strings with length 1
Methods: charAt, charCodeAt, fromCharCode, indexOf, lastIndexOf,
replace, split, substring, toLowerCase, toUpperCase
Property: length
The only operator: +

ĐẠI HỌC CẦN THƠ


CTU
30 [Link] 30
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

String and Number Conversion


Converse between string and number:
let count = 10;
let s1 = "" + count; //"10"
let s2 = count + " student"; //"10 student"
let n1 = parseInt("10 student"); //10
let n2 = parseFloat("blablabla"); //NaN
let s = [Link](); //"10"
let n3 = Number(true); //1
let n4 = Number(""); //0
Get a character in a string at a specified position:
let s = "Hello World";
let firstLetter = s[0]; //"H"
let firstLetter = [Link](0); //"H"

ĐẠI HỌC CẦN THƠ


CTU
31 [Link] 31
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Boolean
Literal values: true and false
Operators: &&, || and !
Non-boolean values can be used as a boolean value with the following
type coercion (implicitly conversion):
null, undefined, 0, NaN, '', and "" are evaluated to false
Everything else is evaluated to true
We can also explicitly convert an arbitrary value to boolean using the
Boolean() constructor or !! operator

ĐẠI HỌC CẦN THƠ


CTU
32 [Link] 32
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Boolean
let complete = true;
let age = 40;
let old = age > 60; //false
let boolValue = Boolean("to ambiguous"); //true
let boolValue1 = !!(""); //false

let username = "...";

if (username) {
// username is defined
}
else {
//username is not defined
}

ĐẠI HỌC CẦN THƠ


CTU
33 [Link] 33
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Equality
JavaScript operators == and != are basically broken: they do an implicit
type conversion before the comparison

'' == '0' // false (two different strings)


'' == 0 // true ('' ~ 0, 0 == 0 is true)
0 == '0' // true (0 ~ '0' => '0' == '0' is true)
NaN == NaN // false (JS rule J)
[''] == '' // true
false == undefined // false
false == null // false
null == undefined // true

ĐẠI HỌC CẦN THƠ


CTU
34 [Link] 34
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Equality
ECMAScript standard added === and !== operators with the better
behavior

'' === '0' // false '' == '0' // false


'' === 0 // false '' == 0 // true
0 === '0' // false 0 == '0' // true
NaN === NaN // still weirdly false NaN == NaN // false
[''] === '' // false [''] == '' // true
false === undefined // false false == undefined // false
false === null // false false == null // false
null === undefined // false null == undefined // true

ĐẠI HỌC CẦN THƠ


CTU
35 [Link] 35
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Null and Undefined


null is a value representing the absence of a value (similar to null value
in Java and nullptr in C++)
undefined is the value given to a variable that has not had a value
However, we can also set a variable's value to undefined 😕

ĐẠI HỌC CẦN THƠ


CTU
36 [Link] 36
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Array
An Object type used to store multiple values in a single variable
0-based indexing
Mutable
Can check size via length property
const list = []; // Creates an empty array

//create a pre-filled array


const groceries = ['milk', 'cocoa puffs'];

groceries[1] = 'kix'; //access an element of the array

ĐẠI HỌC CẦN THƠ


CTU
37 [Link] 37
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Arrays
An array can be used as a list, queue, stack, etc.
Basic methods:
• push/pop: add/remove the element at the end, return an element
• shift/unshift: remove/add an element at the head, return an element
• concat: joints two or more arrays, return the jointed array
• splice: add/remove elements from an array, return the array after
adding/removing
• sort/reserve: soft/reverse the order of elements in the array, return
the result after sorted, reserved
• slice: select a part of an array, return the selected part
[Link]
ĐẠI HỌC CẦN THƠ
CTU
38 [Link] 38
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Arrays
const a = ["Truc", "Lan"];
[Link](); //a=["Lan", "Truc"]
[Link]("Cuc"); //a=["Lan", "Truc", "Cuc"]
[Link]("Mai"); //a=["Mai", "Lan", "Truc", "Cuc"]

const b = [Link](1, 3);


[Link](2, 1, "Tung", "Dao"); //a=["Mai","Lan","Tung","Dao","Cuc"]
[Link](); //a=["Mai", "Lan", "Tung", "Dao"]
[Link](); //a=["Lan", "Tung", "Dao"]

let i = [Link]("Tung"); //1

ĐẠI HỌC CẦN THƠ


CTU
39 [Link] 39
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Array Iteration Methods


Simple for loop (usually combined with the length property)
for ... of statement
[Link]():
calls a callback function once for each array element
The callback function takes 3 parameters: item value, the index and the
array itself
let iterable = [10, 20, 30]; let iterable = [10, 20, 30];
for (const value of for (let value of iterable)
iterable) { {
[Link](value); value += 1;
} [Link](value);
}

ĐẠI HỌC CẦN THƠ


CTU
40 [Link] 40
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Date
The Date class is used to manipulate date and time data types.
Create Date:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds,
milliseconds);
Methods:
getDate(), getDay(), getMonth(), getFullYear()
getHours(), getMinutes(), getSeconds(), getMilliseconds()
setDate(), setMonth(), setFullYear()
setHours(), setMinutes(), setSeconds(), setMilliseconds()

Date object reference: [Link]

ĐẠI HỌC CẦN THƠ


CTU
41 [Link] 41
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Date
Example:
let today = new Date()
let d1 = new Date("October 13, 1975 11:13:00")
let d2 = new Date(79,5,24)
let d3 = new Date(79,5,24,11,33,0)

let myDate = new Date();


[Link](2010,0,14);

let myDate1 = new Date();


[Link]([Link]()+5)

ĐẠI HỌC CẦN THƠ


CTU
42 [Link] 42
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Date
Example:
let x = new Date();
[Link] (2100, 0, 14);
let today = new Date();

if (x > today)
{
alert("Today is before 14th January 2100");
}
else
{
alert("Today is after 14th January 2100");
}

ĐẠI HỌC CẦN THƠ


CTU
43 [Link] 43
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

RegExp Type
Regular expression:
A sequence of characters that forms a search pattern
Regex is a common shorthand for a regular expression
JavaScript RegExp is an Object for handling Regular Expressions
Syntax
let txt=new RegExp(pattern,modifiers); or
let txt=/pattern/modifiers;
Pattern: defines the pattern of the expression.
Modifiers: specifies whether the search should be global and case-
sensitive.

ĐẠI HỌC CẦN THƠ


CTU
44 [Link] 44
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Modifiers
g - Performs a global match (find all)
i - Performs case-insensitive matching
m – Performs Multiline mode matching
Example:
// Match all instances of "at" in a string.
var pattern1 = /at/g;
//Match the first instance of "bat" or "cat",
//regardless of case
var pattern2 = /[bc]at/i;

ĐẠI HỌC CẦN THƠ


CTU
45 [Link] 45
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

RegExp Object
Brackets ([]): characters enclosed in square brackets [].

ĐẠI HỌC CẦN THƠ


CTU
46 [Link] 46
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

RegExp Object
Metacharacter: characters with a special meaning.

ĐẠI HỌC CẦN THƠ


CTU
47 [Link] 47
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

RegExp Object
Quantifiers: define the numbers of characters or expressions to match.

ĐẠI HỌC CẦN THƠ


CTU
48 [Link] 48
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

RegExp Object
Common example:
Email Address: \b[A-z0-9._%+-]+@[A-z0-9.-]+\.[A-z]{2,6}\b
Date String: dd/mm/yyyy
(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)[0-9]{2}
International phone number: ^\+(?:[0-9] ?){6,14}[0-9]$
Integer: \b\d+\b
Text with letters and digits:
^[A-Z0-9]+$
Text with length from 1 to 10:
^[A-Z]{1,10}$

ĐẠI HỌC CẦN THƠ


CTU
49 [Link] 49
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

RegExp Object
Example:

ĐẠI HỌC CẦN THƠ


CTU
50 [Link] 50
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Condition Statements – if/else


Syntax:
if (condition1) {
//block of code to be executed if condition1 is true
} else if (condition2) {
//block of code to be executed if the condition1 is false and condition2 is true
}
...
else {
//block of code to be executed if the condition1 is false and condition2 is false
}

ĐẠI HỌC CẦN THƠ


CTU
51 [Link] 51
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Condition Statements – if/else


var d = new Date();
var t = [Link]();
[Link]("<h4>" + d + "</h4>");
[Link]("<h3>");
if (t < 12) {
[Link]("Good morning!"); }
else if (t < 18) {
[Link]("Good afternoon!"); }
else {
[Link]("Good evening!");
}
[Link]("</h3>");

ĐẠI HỌC CẦN THƠ


CTU
52 [Link] 52
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Condition Statement – switch/case


Syntax:
switch (expression) {
case x:
//code block to be executed when expression = x
break;
case y:
// code block to be executed when expression = y
break;
...
default:
// code to be executed when all above cases not matched
}

ĐẠI HỌC CẦN THƠ


CTU
53 [Link] 53
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Condition Statement – switch/case


let d = new Date();
[Link]("<h4>" + d + "</h4>");
[Link]("<h3>");
switch ([Link]()) {
case 0:
case 6:
[Link]("Have a lovely weekend!");
break;
default:
[Link]("Hace a nice working day!");
}
[Link]("</h3>");

ĐẠI HỌC CẦN THƠ


CTU
54 [Link] 54
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Loop – for
Syntax:
for (statement 1; statement 2; statement 3) {
//code block to be executed
}
Example:
for (let i = 1; i <= 6; i++) {
[Link]("<h" + i + ">");
[Link]("Heading " + i);
[Link]("</h" + i + ">");
}

ĐẠI HỌC CẦN THƠ


CTU
55 [Link] 55
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

Loop – while, do/while


Syntax:
while (condition) {
// code block to be executed
}

do {
//code block to be executed
} while (condition);

ĐẠI HỌC CẦN THƠ


CTU
56 [Link] 56
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

break statement
Used to jump out a loop or a switch statement and continue executing the
code after the loop or switch
let count = 0;
while (true) {
count++;
let r = [Link]([Link]() * 10);
[Link](r + " ");
if (r == 5) {
[Link]("<p>Found '5' after "
+ count + " times</p>");
break;
}
}

ĐẠI HỌC CẦN THƠ


CTU
57 [Link] 57
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics

continue statement
The continue statement jumps over an iteration of a loop
The condition of the loop is checked for a new iteration
for (let i = 0; i <= 10; i++) {
if (i % 2 == 0)
continue;
[Link](i + " ");
}

ĐẠI HỌC CẦN THƠ


CTU
58 [Link] 58
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
Content
1. Introduction
2. Using JavaScript in an HTML documents
3. JS language basics
4. JS functions
5. DOM
6. OOP in JS

ĐẠI HỌC CẦN THƠ


CTU
59 [Link] 59
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Functions

Function Declaration
Syntax:
function func_name(parameters) {
//function body (statements)
}
A function hasn’t been executed until it is called
A function call can be made before its declaration (hoisting)
hello("Messi");

function hello(name) {
[Link]("Hello " + name);
}

ĐẠI HỌC CẦN THƠ


CTU
60 [Link] 60
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Functions

Function Expression
A JS function can also be defined using an expression
let x = function (a, b) {return a * b};
let z = x(4, 3);
alert(z); //alert “12”

The above function is actually an anonymous function (no name)


The function is referenced by the variable and it can be called using the
variable
This also allow to use the function as a parameter or return value of a
function

ĐẠI HỌC CẦN THƠ


CTU
61 [Link] 61
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Functions

Function Expression
function lessthan(a, b) { return a < b;}
function sort(lessthan, arr) { //pass function as a parameter
for (i=0; i<[Link]-1; i++) {
for (j=i+1; j<[Link]; j++) {
if (lessthan(arr[j], arr[i]))
swap(arr[i], arr[j]);
}
function d() {
}
function e() {
}
alert('E’);
}
return e; //returns function e()
}
d()(); //alerts 'E'
ĐẠI HỌC CẦN THƠ
CTU
62 [Link] 62
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Functions

Arrow Functions
Introduced in ES6
Allow us to write shorter function syntax:
Regular syntax and function expression:

function hello() { let hello = function


return 'Hello'; () {
} return 'Hello';
}
Arrow function:
hello = () => { hello = () => 'Hello';
return 'Hello';
hello = (val) => 'Hello ' + val;
}
hello = val => 'Hello ' + val;

If a function has only one statement, we can remove the


brackets and the return keyword
ĐẠI HỌC CẦN THƠ
CTU
63 [Link] 63
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Functions

Function Parameters
Function parameters (formal parameter) are the names listed in the function
definition
Function arguments (actual parameter) are the real values passed to (and
received by) the function
Parameter rules:
• JS function definitions do not specify datatype for parameters
• JS functions don’t check the datatype of the passed arguments
• JS functions do not check the number of arguments received
The built-in object arguments contains an array of the arguments

ĐẠI HỌC CẦN THƠ


CTU
64 [Link] 64
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Functions

Function Parameters
x = findMax(1, 123, 500, 115, 44, 88);

function findMax() {
var i;
var max = -Infinity;
for (i = 0; i < [Link]; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}

ĐẠI HỌC CẦN THƠ


CTU
65 [Link] 65
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Functions

Pass-by-Reference & Pass-by-Value


Objects are pass by reference:
The change of the object properties are reflected outside the function

Arguments are pass by value:


The function only gets to know the value, not the argument’s location
Change to arguments are not reflected outside the function

ĐẠI HỌC CẦN THƠ


CTU
66 [Link] 66
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
Content
1. Introduction
2. Using JavaScript in an HTML documents
3. JS language basics
4. JS functions
5. DOM
6. OOP in JS

ĐẠI HỌC CẦN THƠ


CTU
67 [Link] 67
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)

What is HTML DOM?


The DOM is a W3C standard for accessing documents, including core,
XML and HTML DOM
The HTML DOM is a standard object model and programming
interface for HTML, which defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements

HTML DOM: a standard for getting, changing, adding,


or deleting HTML elements
ĐẠI HỌC CẦN THƠ
CTU
68 [Link] 68
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)

HTML DOM Model


The HTML DOM model is constructed as a tree of objects
When a web page is loaded, the browser creates a Document Object
Model of the page

ĐẠI HỌC CẦN THƠ


CTU
69 [Link] 69
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)

HTML DOM Model


The objects in the hierarchical tree are called nodes
Basic node types:
• Document node (Node.DOCUMENT_NODE, 9): represents the entire
document (the root-node of the DOM tree, children: Elements)
• Element node (Node.ELEMENT_NODE, 1): represents an element
(children: Elements, Texts, Comments)
• Text node (Node.TEXT_NODE, 3): represents textual content in an
element or attribute (children: none)
• Attribute node (Node.ATTRIBUTE_NODE, 2): represents an
attribute (children: none)

ĐẠI HỌC CẦN THƠ


CTU
70 [Link] 70
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
HTML DOM Model
Document Object Model (DOM)

ĐẠI HỌC CẦN THƠ


CTU
71 [Link] 71
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)

HTML DOM Methods


A method is an action that we can perform on HTML elements

Methods Description
Selecting HMTL element
[Link](id) Find an element by element id
[Link](tag) Find elements by tag name
[Link](class) Find elements by class name
[Link](css selectors) Returns the first child element that
matches the given CSS selector(s)
[Link](css selectors) Returns all elements that matches
the given CSS selector(s)

ĐẠI HỌC CẦN THƠ


CTU
72 [Link] 72
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)

HTML DOM Methods


A method is an action that we can perform on HTML elements

Methods Description
Adding and Deleting elements
[Link](element) Create an HTML element
[Link](text) Create a text node
[Link](node) Add an HTML element
[Link](node) Remove an HTML element
[Link](new, old) Replace an HTML element
[Link](text) Write into the HTML output stream

ĐẠI HỌC CẦN THƠ


CTU
73 [Link] 73
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)

HTML DOM Properties


Properties: values (of HTML elements) that we can set or change
Each type of node has its own set of attributes
.innerText: the text content of the specified node (and all its
descendants)
.innerHTML: the HTML content of the specified node
.nodeValue: the node value of the specified node
.nodeName: the name of the specified node
.parentNode: the parent of the specified node (Node object)
.childNodes: the child nodes (NodeList object)
.attributes: attributes of the specified node (NamedNodeMap obj.)
Full list: [Link]
ĐẠI HỌC CẦN THƠ
CTU
74 [Link] 74
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
HTML DOM Properties
Document Object Model (DOM)

ĐẠI HỌC CẦN THƠ


CTU
75 [Link] 75
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)

HTML DOM Properties


nodeName:
• Element node: tag name (e.g. “P”, “IMG”, etc.)
• Attribute node: attribute name (e.g. “src”, ”href”, etc.)
• Text/Document node: “#text”, “#document”
nodeValue:
• Element node: “undefine”
• Text node: text value of the node
• Attribute node: value of the attribute
Note: to access a property value, using the syntax
<node>.<attribute_name>

ĐẠI HỌC CẦN THƠ


CTU
76 [Link] 76
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)

Change Element Content and Attribute


<html>
<body>
<p id="par1">Hello World</p>
<p><img id="img1" src="[Link]"/>
<img id="img2" src="[Link]"/>
</p>
<script>
let p1 = [Link]("par1");
[Link] = "New text";
let m2 = [Link]("img2");
[Link] = "[Link]";
</script>
</body>
</html>
ĐẠI HỌC CẦN THƠ
CTU
77 [Link] 77
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)

Change Element Style


Syntax: <node>.style.<property> = <value>

<body>
<p id="par1">The first paragraph</p>
<p id="par2">The second paragraph</p>
<script>
let p1 = [Link]("par1");
[Link] = "x-large";
let p2 = [Link]("par2");
[Link] = "blue";
[Link] = "2px dotted #0000FF";
</script>
</body>
ĐẠI HỌC CẦN THƠ
CTU
78 [Link] 78
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)

Change Element Class


Syntax: <node>.className = <classname>
<head>
<style>
.blue {color: blue; border: 2px dotted #0000FF;}
.big {font-size: x-large;}
</style>
</head>
<body>
<p id="par1">The first paragraph</p>
<p id="par2">The second paragraph</p>
<script>
[Link]("par1").className = "big";
[Link]("par2").className = "blue";
</script>
</body>
ĐẠI HỌC CẦN THƠ
CTU
79 [Link] 79
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)

Creating new HTML element


<body>
<div id="div1">
<p id="par1">The first paragraph</p>
<p id="par2">The second paragraph</p>
</div>
<script>
const p1 = [Link]("p");
const node = [Link]("This is new.");
[Link](node);
const element = [Link]("div1");
[Link](p1);
// [Link](para, child);
</script>
80</body>
CTU
ĐẠI HỌC CẦN THƠ
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
[Link] 80
• Document Object Model (DOM)

Remove HTML element


<body>
<div id="div1">
<p id="par1">The first paragraph</p>
<p id="par2">The second paragraph</p>
</div>
<script>
const parent = [Link]("div1");
const element = [Link]("par1");
[Link]();
// [Link](element)
</script>
</body>

ĐẠI HỌC CẦN THƠ


CTU
81 [Link] 81
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)

Replacing HTML element


<body>
<div id="div1">
<p id="par1">The first paragraph</p>
<p id="par2">The second paragraph</p>
</div>
<script>
const p1 = [Link]("p");
const node = [Link]("This is new.");
[Link](node);
const parent = [Link]("div1");
const element = [Link]("par1");
[Link](p1, element);
</script>
</body>
ĐẠI HỌC CẦN THƠ
CTU
82 [Link] 82
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Events

HTML Events
HTML provides event handler attributes to use JS code to handle the
events
<element event='some JS code'>

Some common HTML events:


• Mouse: onclick, ondblclick, onmousedown, onmousemove,
onmouseover, onmouseout, onmouseup
• Keyboard: onkeypress, onkeyup, onkeydown
• Form: onblur, onchange, onfocus, onsubmit, onselect
• Frame/Object: onload, onresize, onscroll

ĐẠI HỌC CẦN THƠ


CTU
83 [Link] 83
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Events

HTML Events
<html>
<head>
<script>
function displayDate(eid) {
let e = [Link](eid);
[Link] = Date();
}
</script>
</head>
<body>
<input type="button" value="Click me!" id="bt1"
onclick="displayDate('demo');"
onmouseover="[Link]='red';"
onmouseout="[Link]='black';"/>
<p id="demo">...</p>
</body>
</html>
ĐẠI HỌC CẦN THƠ
CTU
84 [Link] 84
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Events

HTML Events
<script>
function prompttext(getf, inp) {
if (getf && ([Link] == "enter your name")) {
[Link] = "";
[Link] = "black";
}
if (!getf && ([Link] == "")) {
[Link] = "enter your name";
[Link] = "gray";
}
}
</script>

<input id="uname" type="text" style="color:gray;"


value="enter your name" onfocus="prompttext(true, this);"
onblur="prompttext(false, this);"/>
ĐẠI HỌC CẦN THƠ
CTU
85 [Link] 85
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Events

DOM Event Listeners


Each DOM object has the following method for event handling:
addEventListener(event name, function name);
event name: the string of name of the event to listen to
function name: the name of the JS function that will be executed when
the event fires (this function gets an Event object as param)
Pros: separate JS code from HTML markup
An event can be handled by multiple functions
To stop listen to an event use the following function:
removeEventListener(event name, function name);
(the parameters are similar to the addEventListerner())

ĐẠI HỌC CẦN THƠ


CTU
86 [Link] 86
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Events

HTML DOM Listeners


<script>
[Link]("myButton").addEventListner("click",
validate);
function validate(event) {
alert("You click the object: " + [Link]);
var x = [Link]("fname").value;
if (x == "")
alert("Name must be filled out");
else
alert("Hello: " + x);
}
</script>
<body>
<p> Name <input type="text" name="fname" id="fname">
<input id="myButton" type="button" value="Click me!">
</p>
</body>
ĐẠI HỌC CẦN THƠ
CTU
87 [Link] 87
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
Content
1. Introduction
2. Using JavaScript in an HTML documents
3. JS language basics
4. JS functions
5. DOM
6. OOP in JS

ĐẠI HỌC CẦN THƠ


CTU
88 [Link] 88
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• OOP in JS

JS Objects
In JS, almost "everything" is an object, except primitives
• Boolean can be objects (if defined with the new keyword)
• Number can be objects (if defined with the new keyword)
• String can be objects (if defined with the new keyword)
• Date are always objects
• Math are always objects
• Regular expressions are always objects
• Arrays are always objects
• Functions are always objects
• Objects are always objects

ĐẠI HỌC CẦN THƠ


CTU
89 [Link] 89
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• OOP in JS

JS Objects
A variable can contain a single value
JS objects:
• A JS object can contain many named values (properties)
• The values are written in pair as name : value
• An object can also contain methods (actions that the object can
performed)
• A method can be considered as a property that contains a function
definition

ĐẠI HỌC CẦN THƠ


CTU
90 [Link] 90
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• OOP in JS

Create a JS Object
Three ways to create an object:
Define and create a single object, using an object literal
var person = {firstName:"John", lastName:"Doe", age:50,
showInfo: function() {
alert([Link]);
}};
Define and create a single object with the keyword new
var person = new Object();
[Link] = "John";
[Link] = 50;
showInfo: function() { alert([Link]); };

ĐẠI HỌC CẦN THƠ


CTU
91 [Link] 91
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• OOP in JS

Create a JS Object
Three ways to create an object (cont):
Define an object constructor function, and then create objects of the
constructed type
function User(uname, pass) {
[Link] = uname;
[Link] = pass;
[Link] = function() {
alert([Link] + ":" + [Link]);
} //showInfo()
} //User

var alibaba = new User("alibaba", "vomc");


[Link](); //alert “alibaba:vomc”

ĐẠI HỌC CẦN THƠ


CTU
92 [Link] 92
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• OOP in JS

Add Object Properties


To add a property to an object, name the property and give it a value:
const scores = {
peach: 100,
mario: 88,
luigi: 91
};
[Link] = 72;
let name = 'wario';
scores[name] = 102;
[Link](scores);

ĐẠI HỌC CẦN THƠ


CTU
93 [Link] 93
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• OOP in JS

Remove Object Properties


To remove a property of an object, use delete:
const scores = {
peach: 100,
mario: 88,
luigi: 91
};
[Link] = 72;
let name = 'wario’;
scores[name] = 102;
delete [Link];
[Link](scores);

ĐẠI HỌC CẦN THƠ


CTU
94 [Link] 94
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• OOP in JS

Iterate through Object Properties


Use the for ... in loop (for each property in the object):
for (key in object) {
//do something with object[key]
}

Example:
for (let name in scores) {
[Link](name + ' got ' + scores[name]);
}

ĐẠI HỌC CẦN THƠ


CTU
95 [Link] 95
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• OOP in JS

Prototype
JS is described as a prototype-based language
Prototype may be considered as a “class” of an object created by an object
constructor function
A prototype is created for every object constructor function
It is used to:
• create static (common) properties for objects
• add properties (inherit) to an existing object created by an object
constructor function

ĐẠI HỌC CẦN THƠ


CTU
96 [Link] 96
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• OOP in JS

Prototype
function Person(first, last) {
[Link] = first;
[Link] = last;
}
var person1 = new Person("John", "Doe");

To add a method for Person:


[Link] = function() {
alert([Link] + " " + [Link]);
};
var person1 = new Person("John", "Doe");
[Link]();

ĐẠI HỌC CẦN THƠ


CTU
97 [Link] 97
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• OOP in JS

Prototype
Add a “static” property for a prototype:
function Person(first, last) {
[Link] = first;
[Link] = last;
[Link]++;
};

[Link] = 0;

var person1 = new Person("John", "Doe");


var person2 = new Person("Doe ", "John");

[Link]("[Link]: " + [Link]);


[Link]("[Link]: " + [Link]);
ĐẠI HỌC CẦN THƠ
CTU
98 [Link] 98
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• OOP in JS

JS Classes
class Dog extends Animal {
Creating classes in ES6: constructor(name, breed) {
//Call the constructor of the parent class
super(name);
[Link] = breed;
class Animal { }
constructor(name) {
[Link] = name; //Overriding the speak method of the parent class
} speak() {
[Link]('${[Link]} barks');
}
speak() {
//New method specific to the Dog class
[Link]('${[Link]} fetch() {
makes a sound'); [Link]('${[Link]}
} fetches a ball');
} }
}

ĐẠI HỌC CẦN THƠ


CTU
99 [Link] 99
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• OOP in JS

Creating Objects
Creating objects in ES6:
//Creating an instance of the child class
let myDog = new Dog('Buddy', 'Golden Retriever’);

//Accessing properties and methods of the child class


[Link]([Link]); //Output: Buddy
[Link]([Link]); //Output: Golden Retriever
[Link](); //Output: Buddy barks
[Link](); //Output: Buddy fetches a ball

ĐẠI HỌC CẦN THƠ


CTU
100 [Link] 100
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
Appendix

ĐẠI HỌC CẦN THƠ


CTU
101 [Link] 101
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Appendix

Alert Box
Used to make sure information comes through to the user
The user will have to click "OK" to proceed
Syntax: [window.]alert("sometext");

ĐẠI HỌC CẦN THƠ


CTU
102 [Link] 102
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Appendix

Confirm Box
Used verify that the user accept something or not
The user will have to click either "OK" or "Cancel" to proceed
If the user clicks "OK", the box returns true.
If the user clicks "Cancel", the box returns false
Syntax: [window.]confirm("sometext");

ĐẠI HỌC CẦN THƠ


CTU
103 [Link] 103
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Appendix

Prompt Box
Used to get an input value from users
The user will have to click either "OK" or "Cancel" to proceed
If the user clicks "OK" the box returns the input value.
If the user clicks "Cancel" the box returns null
Syntax: [window.]prompt("sometext","defaultText");

ĐẠI HỌC CẦN THƠ


CTU
104 [Link] 104
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
Exception
try … catch is used to catch an exception occurs
Syntax:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}

Finally is optional

ĐẠI HỌC CẦN THƠ 105


CTU
105 [Link] 105
Cộng đồng – Toàn diện – Ưu việt
1/7/26 Khoa mạng máy tính & truyền thông
Exception
Example:

ĐẠI HỌC CẦN THƠ 106


CTU
106 [Link] 106
Cộng đồng – Toàn diện – Ưu việt
1/7/26 Khoa mạng máy tính & truyền thông
• Appendix

Further Reading
Methods of JS basic datatypes:
• String: indexOf(), lastIndexOf(), slice(), split(), trim(), etc.
• Number: isFinite(), isInteger(), toString(), etc.
• Math: abs(), min(), max(), sqrt(), round(), random(), etc.
JS regular expression: [Link]
JS debugging: [Link]
JS style guide: [Link]
JS Browser Object Model (BOM, allows JS to "talk to" the browser): Window, Screen,
Location, History, Navigation, Cookies

ĐẠI HỌC CẦN THƠ


CTU
107 [Link] 107
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
Question?
Chapter 4 – JavaScript

ĐẠI HỌC CẦN THƠ


CTU
108 [Link] 108
Cộng đồng – Toàn diện – Ưu việt
Faculty of Computer Network and Communication

You might also like