0% found this document useful (0 votes)
4 views67 pages

JavaScript Basics and Features Explained

The document provides an overview of JavaScript, covering its history, features, and relationship with HTML and CSS. It discusses client-side programming, common scripting tasks, data types, variables, and operators in JavaScript. Additionally, it explains how JavaScript can be used both in the browser and on the server side with NodeJS.
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)
4 views67 pages

JavaScript Basics and Features Explained

The document provides an overview of JavaScript, covering its history, features, and relationship with HTML and CSS. It discusses client-side programming, common scripting tasks, data types, variables, and operators in JavaScript. Additionally, it explains how JavaScript can be used both in the browser and on the server side with NodeJS.
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

JavaScript

Most used programming languages as of 2024

src: [Link]
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

2
Content

•Scripts
•common tasks for client-side scripts

•JavaScript
•data types & expressions
•control statements
•functions & libraries
•date, document, string, array, user-defined classes

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


School of Information and Communication Technology

3
Client-Side Programming

•HTML is good for developing static pages


•can specify text/image layout, presentation, links, …
•Web page looks the same each time it is accessed

•Client-side programming
•programs are written in a separate programming (or
scripting) language, e.g., JavaScript,
•programs are embedded in the HTML of a Web page
•the browser executes the program as it loads the page,
integrating the dynamic output of the program with
the static content of HTML
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

4
Common Scripting Tasks

•adding dynamic features to Web pages


•validation of form data
•image rollovers
•time-sensitive or random page elements
•handling cookies

•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

5
JavaScript/ ECMAScript

Year ECMA Browser


1995 Javascript was invented by Brendan Eich
1996 Netscape 2 has Javascript 1.0
1997 Javascript become an ECMA standard (ECMA-262)
1997 ES1 IE4 was the first browser to support ES1
2015 ES6 ECMAScript6 was released
2016 ECMAScript 2016
2016-201 Full support for ECMAScript2016 by modern
7 browsers (Chrome, Safari, Firefox, Edge)

• ECMA - European Computer Manufacturers Association


• ECMAScript is a standard for scripting languages including
JavaScript, JScript, and ActionScript
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

6
JavaScript

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


School of Information and Communication Technology

7
JavaScript

● Once the web was already


being used they realize
people wanted to interact
with the websites in a more
meaningful way.
● So they added an Interpreter
to execute a script language
that could modify the content
of the web dynamically.
● Brendan Eich was tasked to
develop it in one week and it
has become one of the most
important languages.

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


School of Information and Communication Technology

8
JavaScript

•JavaScript is mainly interpreted, but modern JavaScript


engines, like V8 (in Google Chrome), SpiderMonkey (in
Firefox) use JIT (Just-In-Time compilation) to boost
performance.
•Execute the code using an interpreter
•Identify frequently used (hot path) code and
compile it into optimized machine code

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


School of Information and Communication Technology

9
JavaScript

● Client-side: JS can run on browsers as a scripting


language that allows you to create dynamically
updating content, control multimedia, animate
images,…
● Server-side: JS can run on server side with the
appearance of NodeJS – a Javascript runtime
environment.

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


School of Information and Communication Technology

10
Features of JavaScript

● It is a Scripting Language and has nothing to do with


Java. Initially, It was named Mocha, then changed to
LiveScript and finally it was named as JavaScript.
● JavaScript is an object-based programming language
that supports polymorphism, encapsulation, and
inheritance as well.
● You can run JavaScript not only in the browser but also
on the server and any device which has a JavaScript
Engine.

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


School of Information and Communication Technology

11
Relationship between HTML, CSS, and JavaScript

Component Role / Purpose Analogy

Defines the structure and 🦴 Skeleton – provides the


HTML
content of a webpage. basic framework.

Controls the style, colors,


👕 Clothes – makes the
CSS layout, and visual
webpage look attractive.
appearance.

🛹 Life / Motion – brings the


Adds interactivity, animation,
JavaScript webpage to life, makes it move
and dynamic behavior.
and respond.

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


School of Information and Communication Technology

12
JavaScript insert code

● There is three ways to execute javascript code in a website:


● Embed the code in the HTML using the <script> tag.
<script> /* some code */ </script>
● Import a Javascript file using the <script> tag:
<script src="[Link]" />
● Inject the code on an event inside a tag:
<button onclick="javascript: /*code*/">press
me</button>

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


School of Information and Communication Technology

13
JavaScript

<!DOCTYPE html>
<html> • Use <script> tag to add
<head> Javascript code to a page
<title>JavaScript Page</title>
</head> • [Link]
<body> ▪ displays text in the page
<script type="text/javascript"> ▪ text can include HTML
[Link]("<p>Hello world!</p>"); tags
[Link](" <p>How are you?</p> ");
</script>
<p>Here is some static text.</p>
</body>

</html>

[Link]

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


School of Information and Communication Technology

14
JavaScript Data Types & Variables

<script>
// Number: ● JavaScript has 8 data types
let weight = 7.5; String
Number
// String: Bigint
let color = "Yellow";
Boolean
// Booleans Undefined: undefined
let x = true; Null: null
Symbol
// Object: Object
const person = {firstName:"John",
lastName:"Doe"};
● variable names contain
// Array object:
const cars = ["Saab", "Volvo"]; letters, digits, an
underscores that start with
// Date object: a letter or an underscore,
const date = new Date("2024-09-25"); case sensitive
</script>

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


School of Information and Communication Technology

15
JavaScript Data Types & Variables

Variables
● A memory location that acts as a container for storing
data is named as a Variable. They are reserved memory
locations.

● You have to use the ‘let’ keyword to declare a variable.

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


School of Information and Communication Technology

16
The Concept of Data Types

let length = 16; // Number


let lastName = "Johnson"; // String
let x = {firstName:"John", lastName:"Doe"}; // Object

let x = 16 + "Volvo";
Result: 16Volvo

let x = "16" + "Volvo”


Result: 16Volvo

● When adding a number and a string, JavaScript will treat the


number as a string.

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


School of Information and Communication Technology

17
The Concept of Data Types

● JavaScript evaluates expressions from left to right. Different


sequences can produce different results:

let x = 16 + 4 + "Volvo";
Result: 20Volvo

let x = "Volvo" + 16 + 4;
Result: Volvo164

● Since the first operand is a string, all operands are treated as


strings.

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


School of Information and Communication Technology

18
JavaScript Data Types & Variables

•Same variable can be used to hold different data types:

<script>
let x; // Now x is undefined
x = 5; // Now x is a Number
x = ”A"; // Now x is a String
</script>

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


School of Information and Communication Technology

19
JavaScript Declaration

• var: function scope or global scope, used in all JS code from 1995 to 2015

• let: block scope, added to JS in 2015

• const: same as let, except the user cannot update it


• Note: use var keyword only in code written for old browsers

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


School of Information and Communication Technology

20
JavaScript Numbers

● JavaScript has only one type of numbers. Numbers can be


written with, or without decimals:
let x1 = 34.00; // Written with decimals
let x2 = 34; // Written without decimals
● Extra large or extra small numbers can be written with
scientific (exponential) notation:
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123

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


School of Information and Communication Technology

21
JavaScript Strings

● A string (or a text string) is a series of characters like "John


Doe". Strings are written with quotes. You can use single or
double quotes:
let carName1 = "Volvo XC60"; // Using double quotes
let carName2 = 'Volvo XC60'; // Using single quotes
● Result:
Volvo XC60
Volvo XC60
● You can use quotes inside a string, as long as they don't match
the quotes surrounding the string:
let answer1 = "It's alright"; // Single quote inside
double quotes
let answer2 = "He is called 'Johnny'"; // Single
quotes inside double quotes
let answer3 = 'He is called "Johnny"'; // Double
quotes inside single quotes
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

22
JavaScript Booleans

● Booleans can only have two values: true or false.

let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false

● Booleans are often used in conditional testing.

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


School of Information and Communication Technology

23
JavaScript Arrays

● JavaScript arrays are written with square brackets. Array


items are separated by commas.
● The following code declares (creates) an array called cars,
containing three items (car names):
const cars = ["Saab", "Volvo", "BMW"];

● Array indexes are zero-based, which means the first item is [0],
second is [1], and so on.

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


School of Information and Communication Technology

24
JavaScript Objects

● JavaScript objects are written with curly braces {}.


● Object properties are written as name: value pairs,
separated by commas.
const person = {firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"};

● The object (person) in the example above has 4


properties: firstName, lastName, age, and eyeColor.

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


School of Information and Communication Technology

25
The typeof Operator

● You can use the JavaScript typeof operator to find the


type of a JavaScript variable.
● The typeof operator returns the type of a variable or an
expression:
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"

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


School of Information and Communication Technology

26
Undefined

● In JavaScript, a variable without a value, has the value


undefined. The type is also undefined.
let car; // Value is undefined, type is undefined
● Any variable can be emptied, by setting the value to undefined.
The type will also be undefined.
car = undefined; // Value is undefined, type is
undefined

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


School of Information and Communication Technology

27
JavaScript Operators & Control Statements

<!DOCTYPE html>
<html>
<body> Operators & control
<script type="text/javascript"> statements:
const distanceToSun = 93.3e6 * 5280
* 12; +, -, *, /, %, ++, --, …
let thickness = .002; ==, !=, <, >, <=, >=
let foldCount = 0;
while (thickness < distanceToSun) &&, ||, !,===,!==
{
thickness *= 2;
foldCount++; if , if-else, switch
}
[Link]("Number of folds = "
while, for, do-while, …
+foldCount);
</script>
</body>
</html>

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


School of Information and Communication Technology

28
Arithmetic Operators

● JavaScript Arithmetic Operators are used


to perform arithmetic on numbers:
● Adding: The addition operator (+) adds
numbers
let x = 5;
let y = 2;
let z = x + y;
● Multiplying
let x = 5;
let y = 2;
let z = x * y;

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


School of Information and Communication Technology

29
Assignment Operators

● Assignment operators assign values to JavaScript variables.

● The addition assignment operator (+=) adds a value to a


variable.
let x = 10;
x += 5; // x will be 10+5=15

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


School of Information and Communication Technology

30
String Operators

● The + operator can also be used to add (concatenate) strings.


let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
The result of text3 will be: John Doe
● The += assignment operator can also be used to add
(concatenate) strings:
let text1 = "What a very ";
text1 += "nice day";
The result of text1 will be: What a very nice day
● Adding two numbers, will return the sum, but adding a number
and a string will return a string.

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


School of Information and Communication Technology

31
Comparison Operators

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


School of Information and Communication Technology

32
Logical and Type Operators

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


School of Information and Communication Technology

33
Bitwise Operators

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


School of Information and Communication Technology

34
Conditional Statements

Conditional statement is a set of


rules performed if a certain condition
is met. The two types of conditional
statements are:
● if
● else if

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


School of Information and Communication Technology

35
Switch Case

The switch statement is used to perform different actions based


on different conditions.

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


School of Information and Communication Technology

36
For loop

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


School of Information and Communication Technology

37
While and do while

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


School of Information and Communication Technology

38
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 just make a direct
assignment (new is implicit)
• word = new String("foo");word = "foo";
properties/methods are called exactly as in C++/Java
• [Link] [Link](0)
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

39
String example: Palindromes

function strip(str) palindrome


{ noon Radar
let copy = "";
for (let i = 0; i < [Link]; i++) { Madam, I'm Adam.
if (([Link](i) >= "A" && [Link](i) <= "Z")
||
([Link](i) >= "a" && [Link](i) <= "z"))
{
copy += [Link](i);
}
• must strip
} non-letters
return copy; • make all chars
}
uppercase in
function isPalindrome(str) order to be
// Assumes: str is a string
// Returns: true if str is a palindrome, else false case-insensitive
{ • finally, traverse
str = strip([Link]());
and compare
for(let i = 0; i < [Link]([Link]/2); i++) { chars
if ([Link](i) != [Link]([Link]-i-1)) {
return false;
}
}
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
return true;
School of Information and Communication Technology

} 40
<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">
const text = prompt("Enter a word or phrase", "Madam, I'm Adam");
if (isPalindrome(text)) {
[Link]("'" + text + "' <b>is</b> a palindrome.");
}
else {
[Link]("'" + text + "' <b>is not</b> a palindrome.");
}
</script>
</body>
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

41
Arrays

• Arrays store a sequence of items, accessible via an index


• since JavaScript is loosely typed, elements do not have to be the same type
• to create an array, allocate space using new (or can assign directly)
let items = new Array(10); // allocates space for 10 items
let items = new Array(); // if no size given, will adjust dynamically
let items = [0,0,0,0,0,0,0,0,0,0]; // can assign size & values []
• to access an array element, use [] (as in C++/Java)
for (i = 0; i < 10; i++) {
items[i] = 0; // stores 0 at each index
}
• the length property stores the number of items in the array
for (i = 0; i < [Link]; i++) {
[Link](items[i] + "<br>"); // displays elements
}

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


School of Information and Communication Technology

42
Array Example
<!DOCTYPE html>
<html>
<head>
<title>Dice Statistics</title>
<script type="text/javascript” src="[Link]">
</script>
</head>
<body>
<script type="text/javascript">
const numRolls = 60000;
const diceSides = 6;
let rolls = new Array(dieSides+1);
for (i = 1; i < [Link]; i++) {
rolls[i] = 0;
}
for(i = 1; i <= numRolls; i++) {
rolls[randomInt(1, dieSides)]++;
}
for (i = 1; i < [Link]; i++) {
[Link]("Number of " + i + "'s = " +rolls[i] + "<br />");
}
</script>
</body>
</html>

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


School of Information and Communication Technology

43
Arrays (cont.)

• Arrays have predefined methods that allow them to be used as stacks,


queues, or other common programming data structures.
let stack = new Array();
[Link]("blue");
[Link](12); // stack is now the array ["blue", 12]
[Link]("green"); // stack = ["blue", 12, "green"]
let item = [Link](); // item is now equal to "green"

let q = [1,2,3,4,5,6,7,8,9,10];
item = [Link](); // item is now equal to 1, remaining
// elements of q move down one position
// in the array, e.g. q[0] equals 2
[Link](125); // q is now the array [125,2,3,4,5,6,7,8,9,10]
[Link](244); // q = [125,2,3,4,5,6,7,8,9,10,244]

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


School of Information and Communication Technology

44
JavaScript Functions

● A JavaScript function is a block of code designed to perform a


particular task.
● A JavaScript function is executed when "something" invokes it
(calls it).
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product
of p1 and p2
}

Why Functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments,
to produce different results.

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


School of Information and Communication Technology

45
Function Syntax

● A JavaScript function is defined with the function keyword,


followed by a name, followed by parentheses ().
● Function names can contain letters, digits, underscores, and
dollar signs (same rules as variables).
● The parentheses may include parameter names separated by
commas: (parameter1, parameter2, ...)
● The code to be executed, by the function, is placed inside curly
brackets: {}

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


School of Information and Communication Technology

46
User-Defined Functions

● no return type for the function (since variables are loosely typed)
● no variable typing for parameters (since variables are loosely typed)
● by-value parameter passing only (parameter gets copy of argument)

function isPrime(n)
{
if (n < 2) {
return false;
}
else if (n == 2) {
return true;
}
else {
for (let i = 2; i <= [Link](n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

47
Function Example

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function isPrime(n)
// Assumes: n > 0
// Returns: true if n is prime
{
// CODE AS SHOWN ON PREVIOUS SLIDE
}
</script>
</head>
<body>
<script type="text/javascript">
let testNum = parseFloat(prompt("Enter a positive integer", "7"));
if (isPrime(testNum)) {
[Link](testNum + " <b>is</b> a prime number.");
}
else {
[Link](testNum + " <b>is not</b> a prime number.");
}
</script>
</body>
</html>
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

48
Another Example

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function randomInt(low, high)
// Assumes: low <= high
// Returns: random integer in range [low..high]
{
return [Link]([Link]()*(high-low+1)) + low;
}
</script>
</head>
<body>
<script type="text/javascript">
const roll1 = randomInt(1, 6);
const roll2 = randomInt(1, 6);
[Link]("<img src='" + roll1 + ".gif'/>");
[Link]("<br/>");
[Link]("<img src='" + roll2 + ".gif'/>");
</script>
</body>
</html>
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

49
JavaScript Libraries

Better still: if you define functions that may be useful to


many pages, store in a separate library file and load the
library when needed load a library using the src attribute
in the script tag

<script type="text/javascript"
src="[Link]">
</script>

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


School of Information and Communication Technology

50
Library Example

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="[Link]">
</script>
</head>
<body>
<script type="text/javascript">
const roll1 = randomInt(1, 6);
const roll2 = randomInt(1, 6);
[Link]("<img src='" + roll1 + ".gif'/>");
[Link]("<br/>");
[Link]("<img src='" + roll2 + ".gif'/>");
</script>
</body>
</html>

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


School of Information and Communication Technology

51
Callback Function

•We can pass functions as parameters to other functions


and call them inside the outer function

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


School of Information and Communication Technology

52
Objects

Objects are used to store keyed collections of various


data and more complex entities. An object contains list of
properties. A property is a “key:value” pair, where key is a
string and value can be anything.

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


School of Information and Communication Technology

53
Objects

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


School of Information and Communication Technology

54
Objects

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


School of Information and Communication Technology

55
Object references

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


School of Information and Communication Technology

56
Math Object

<!DOCTYPE html> Math object contains functions and


<html> constants
<head>
<title>Random Dice Rolls</title> [Link]
</head> [Link]
<body> [Link]
<div style="text-align:center"> [Link]
<script type="text/javascript"> [Link]
const roll1 = [Link]([Link]()*6) + 1; [Link]
const roll2 = [Link]([Link]()*6) + 1; [Link]
[Link](” [Link]
<img src=‘" + roll1 +".gif‘/>");
[Link](” [Link]
Math.E
<img src=‘" + roll2 + ".gif‘/>");
</script>
[Link] function returns a real
</div>
number in [0..1)
</body>
</html>

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


School of Information and Communication Technology

57
Math Object

• ceil(4.7)=? 5
• floor(4.7)=? 4
• round(4.7)=? 5

• ceil(4.2)=? 5
• floor(4.2)=? 4
• round(4.2)=? 4

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


School of Information and Communication Technology

58
Date Object

• Date object can be used to access the date and time


• create a Date object
const today = new Date(); // sets to current date & time
const newYear = new Date(2025,0,1); //sets to Jan 1, 2025 12:00AM

• methods include:
getFullYear() year (yyyy)
getMonth() month (0, 11)
getDate() day (1, 31)
getDay() weekday (0, 6)
getHours() hour (0, 23)
getMinutes() minute (0, 59)
getSeconds() second (0, 59)
getMilliseconds() millisecond (0, 999)
getTime() milliseconds since 1/1/1970 00:00:00 UTC (Unix epoch)

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


School of Information and Communication Technology

59
Date Example

<body>
Time when page was loaded:
<script type="text/javascript">
const now = new Date(); by default, a date will be
[Link]("<p>" + now + "</p>"); displayed in full, e.g.,
let time = "AM";
let hours = [Link](); Wed, Sep 25 22:55:20 2024
if (hours > 12) {
hours -= 12; can pull out portions of the date
time = "PM" using the methods and display as
}
else if (hours == 0) {
desired
hours = 12;
} here, determine if "AM" or
[Link]("<p>" + hours + ":" + "PM" and adjust so hour
[Link]() + ":" + between 1-12
[Link]() + " " +
time + "</p>"); 10:55:20 PM
</script>
</body>

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


School of Information and Communication Technology

60
Another Example

<body>
<p>Elapsed time in this year:
<script type="text/javascript">
const now = new Date();
const newYear = new Date(2025,0,1);
let secs = [Link]((now-newYear)/1000);
let days = [Link](secs / 86400);
secs -= days*86400;
let hours = [Link](secs / 3600);
secs -= hours*3600;
let minutes = [Link](secs / 60);
secs -= minutes*60
[Link](days + " days, " +
hours + " hours, " +
minutes + " minutes, and " +
secs + " seconds.");
</script>
</p>
</body>
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

61
Document Object

<body>
<table width="100%"> [Link](…)
<tr> method that displays text in the
<td><i> page
<script type="text/javascript">
[Link]([Link]);
[Link]
</script>
</i></td> property that gives the location
<td style="text-align: of the HTML document
right;"><i>
<script type="text/javascript"> [Link]fied
[Link]([Link]); property that gives the date &
</script> time the HTML document was
</i></td> last changed
</tr>
</table>
</body>

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


School of Information and Communication Technology

62
User-Defined Objects

• User can create a class by using keyword “class”

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


School of Information and Communication Technology

63
Garbage collection

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


School of Information and Communication Technology

64
Garbage collection

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


School of Information and Communication Technology

65
Garbage collection

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


School of Information and Communication Technology

66
Exercise

• Do 5 exercises on Algorithms and Data Structures


• Link:
[Link]
-data-structures/#javascript-algorithms-and-data-structures-pr
ojects

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


School of Information and Communication Technology

67

You might also like