0% found this document useful (0 votes)
5 views40 pages

JavaScript Programming Essentials Guide

The document provides an overview of JavaScript, including its history, data types, and usage in client-side and server-side programming. It covers common scripting tasks, JavaScript syntax, functions, and libraries, along with practical examples of how to implement JavaScript in HTML. Additionally, it discusses concepts like objects, garbage collection, and string manipulation.

Uploaded by

viusiachay
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)
5 views40 pages

JavaScript Programming Essentials Guide

The document provides an overview of JavaScript, including its history, data types, and usage in client-side and server-side programming. It covers common scripting tasks, JavaScript syntax, functions, and libraries, along with practical examples of how to implement JavaScript in HTML. Additionally, it discusses concepts like objects, garbage collection, and string manipulation.

Uploaded by

viusiachay
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 Inform ation and Com m unication 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 Inform ation and Com m unication 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 Inform ation and Com m unication 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 Inform ation and Com m unication 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- Full support for ECMAScript2016 by modern
2017 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 Inform ation and Com m unication Technology

6
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 opitimzed machine code

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


School of Inform ation and Com m unication Technology

7
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 Inform ation and Com m unication Technology

8
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 Inform ation and Com m unication Technology

9
JavaScript Data Types & Variables

<script>
// Number: • JavaScript has 8 data types
let weight = 7.5; String
// String: Number
let color = "Yellow"; Bigint
Boolean
// Booleans Undefined: undefined
let x = true;
Null: null
// Object: Symbol
const person = {firstName:"John", Object
lastName:"Doe"};

// Array object:
• variable names contain
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");
</script>
case sensitive

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


School of Inform ation and Com m unication Technology

10
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 Inform ation and Com m unication Technology

11
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 Inform ation and Com m unication Technology

12
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 Inform ation and Com m unication Technology

13
User-Defined Functions

• function definitions are similar to C++/Java, except:


• 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 Inform ation and Com m unication Technology

14
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 Inform ation and Com m unication Technology

15
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 Inform ation and Com m unication Technology

16
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 Inform ation and Com m unication Technology

17
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 Inform ation and Com m unication Technology

18
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 Inform ation and Com m unication Technology

19
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 Inform ation and Com m unication Technology

20
Objects

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


School of Inform ation and Com m unication Technology

21
Objects

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


School of Inform ation and Com m unication Technology

22
Object references

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


School of Inform ation and Com m unication Technology

23
Garbage collection

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


School of Inform ation and Com m unication Technology

24
Garbage collection

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


School of Inform ation and Com m unication Technology

25
Garbage collection

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


School of Inform ation and Com m unication Technology

26
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 Inform ation and Com m unication Technology

27
String example: Palindromes

function strip(str) palindrome


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

28
<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 Inform ation and Com m unication Technology

29
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]
<img src=‘" + roll2 + ".gif‘/>"); Math.E
</script>
</div> [Link] function returns a real
</body> number in [0..1)
</html>

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


School of Inform ation and Com m unication Technology

30
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 Inform ation and Com m unication Technology

31
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 Inform ation and Com m unication Technology

32
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 Inform ation and Com m unication Technology

33
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 Inform ation and Com m unication Technology

34
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 Inform ation and Com m unication Technology

35
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
}
else if (hours == 0) { as 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 Inform ation and Com m unication Technology

36
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 Inform ation and Com m unication Technology

37
Document Object

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

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


School of Inform ation and Com m unication Technology

38
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 Inform ation and Com m unication Technology

39
Exercise

• Do 5 exercises on Algorithms and Data Structures


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

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


School of Inform ation and Com m unication Technology

40

You might also like