JavaScript Basics and Features Explained
JavaScript Basics and Features Explained
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
3
Client-Side Programming
•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
5
JavaScript/ ECMAScript
6
JavaScript
7
JavaScript
8
JavaScript
9
JavaScript
10
Features of JavaScript
11
Relationship between HTML, CSS, and JavaScript
12
JavaScript insert code
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]
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>
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.
16
The Concept of Data Types
let x = 16 + "Volvo";
Result: 16Volvo
17
The Concept of Data Types
let x = 16 + 4 + "Volvo";
Result: 20Volvo
let x = "Volvo" + 16 + 4;
Result: Volvo164
18
JavaScript Data Types & Variables
<script>
let x; // Now x is undefined
x = 5; // Now x is a Number
x = ”A"; // Now x is a String
</script>
19
JavaScript Declaration
• var: function scope or global scope, used in all JS code from 1995 to 2015
20
JavaScript Numbers
21
JavaScript Strings
22
JavaScript Booleans
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
23
JavaScript Arrays
● Array indexes are zero-based, which means the first item is [0],
second is [1], and so on.
24
JavaScript Objects
25
The typeof Operator
26
Undefined
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>
28
Arithmetic Operators
29
Assignment Operators
30
String Operators
31
Comparison Operators
32
Logical and Type Operators
33
Bitwise Operators
34
Conditional Statements
35
Switch Case
36
For loop
37
While and do while
38
String Object
39
String example: Palindromes
} 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
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>
43
Arrays (cont.)
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]
44
JavaScript Functions
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.
45
Function Syntax
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
<script type="text/javascript"
src="[Link]">
</script>
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>
51
Callback Function
52
Objects
53
Objects
54
Objects
55
Object references
56
Math Object
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
58
Date Object
• 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)
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>
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>
62
User-Defined Objects
63
Garbage collection
64
Garbage collection
65
Garbage collection
66
Exercise
67