0% found this document useful (0 votes)
10 views

02_ES6_TypeScript

The document provides an overview of Full Stack Development focusing on JavaScript (ES5+ and TypeScript), detailing its history, new features, and asynchronous programming concepts. It covers the evolution of JavaScript from its inception in 1995 to the latest features introduced in ES2023, including promises and async/await for handling asynchronous operations. Additionally, it introduces TypeScript as a statically typed superset of JavaScript, highlighting its benefits and features such as type inference, interfaces, and generics.

Uploaded by

nphuyen.personal
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)
10 views

02_ES6_TypeScript

The document provides an overview of Full Stack Development focusing on JavaScript (ES5+ and TypeScript), detailing its history, new features, and asynchronous programming concepts. It covers the evolution of JavaScript from its inception in 1995 to the latest features introduced in ES2023, including promises and async/await for handling asynchronous operations. Additionally, it introduces TypeScript as a statically typed superset of JavaScript, highlighting its benefits and features such as type inference, interfaces, and generics.

Uploaded by

nphuyen.personal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

RMIT Classification: Trusted


Full Stack Development – COSC2769/COSC2808

ES5+ & TypeScript

1
RMIT Classification: Trusted

Agenda

• Brief history
• New features
• Asynchronous programming
▪ TypeScript

22
RMIT Classification: Trusted

Brief history

• 1995: birth of JavaScript


• 1997: JavaScript was standardized by European Computer Manufacturers
Association (ECMA)
• 1999: ECMAScript 3 released with added regular expression, better string
handling, new control statements, try/catch exception handling, etc.
• 2003: ECMAScript 4 was abandoned, and many proposed features have
been completely dropped
• 2009: ES5 released with strict mode, JSON support, and more array
manipulation
33
RMIT Classification: Trusted

Brief history (2)

• 2015: ES6 released with significant improvements, including classes,


modules, arrow functions, promises, template literals, promises
• 2016: ES2016 released. New features include exponentiation operator (**),
await and async keywords for asynchronous programming
• 2017 to 2023: ES2017 to ES2023 released. More features have been added
into the language, making it more powerful and easy to work with

44
RMIT Classification: Trusted

New features

• Some notable new (or not


so new) features in ES5
• "use strict": a directive to
indicate that code should
be executed in "strict
mode". Read this article to
learn more about strict
mode

55
RMIT Classification: Trusted

New features (2)

• Array.isArray() method: check if an object is an array


• forEach()
• map()
• filter()
• reduce()
• every()
• some()

66
RMIT Classification: Trusted

New features (3)


• JSON.parse(): convert a string to a JavaScript object (use case: when you receive data from the server)
• JSON.stringify(): convert a JavaScript object to a string (use case: when you want to send an object to the server)

77
RMIT Classification: Trusted

New features (4)

• Object.keys(): return an array with the keys of an object


• Trailing commas: allow trailing commas in object and array definition

88
RMIT Classification: Trusted

New features (5)

• New features in ES6


• let and const keywords
• Arrow functions
• Object destructuring:
selectively assign object
properties to variables

99
RMIT Classification: Trusted

New features (6)

• Array destructuring: selectively assign array values to variables


• The … (spread) operator: expand an iterable (for example, an array) into
more elements

10
10
RMIT Classification: Trusted

New features (7)

• The … (spread) operator - more examples: function arguments (left - top), copying an array

(middle), add/modify object properties (right), spread a string (left - bottom)

11
11
RMIT Classification: Trusted

New features (8)


• for of loop (over an array, string)
• Map data structure to store key-value pairs
• Set data structure to store collection of unique values

12
12
RMIT Classification: Trusted

New features (9)

• The class keyword to define templates for creating JavaScript objects

• The Promise object (covered later)

• Default parameters

• Function rest parameter: accept an indefinite number of arguments

13
13
RMIT Classification: Trusted

New features (10)

• includes(), startsWith(), endsWith() methods (String)


• Array find() and findIndex(): return the value/index of the first element that
satisfy a test function
• The test function can accept three arguments: the element value, the
element index, and the array itself

14
14
RMIT Classification: Trusted

Asynchronous programming

▪ NodeJS runs JavaScript code in a single-threaded and non-blocking mode


• Single-threaded: JavaScript can execute only one command at a time within a single
thread
• Non-blocking: I/O operations that take long time to execute do not stop the execution of
other commands
• Event loop: a mechanism that continuously check if there are any events (for example,
a completed I/O operation) that need their callback functions to be executed
▪ Asynchronous programming in JavaScript
• Event handler
• Promise
• async/await
• Worker

15
15
RMIT Classification: Trusted

Event handler

▪ Event handler
• Provide a function which is called a callback function
• The function will be called when the event happens

▪ Using callback function


• function someFunc(param, callback) {
// do something with param
param += 1;
callback(param);
}
• someFunc(123, (v) => {
console.log(v);
});

16
16
RMIT Classification: Trusted

Callback function

▪ A series of function calls in


ordered

▪ How to do the same with


callback functions?
▪ Which version is easier to
read and understand?
▪ Result: "callback hell"

17
17
RMIT Classification: Trusted

Promise

▪ Promises are the foundation of asynchronous programming in modern


JavaScript. A promise represents the eventual completion or failure of an
asynchronous operation and its resulting value
▪ When a promise object is created, its value is unknown and its state is
pending. Eventually, the promise object is either fulfilled or rejected
▪ You provide functions to run if the promise is fulfilled or rejected respectively
▪ Let’s define a promise that
• Generate a random number from 0 to 1
• If the generated number is >= 0.5, the promise is fulfilled, the value is returned
• Otherwise, the promise is rejected, the value is returned

18
18
RMIT Classification: Trusted

Promise (2)
▪ let myPromise = new Promise(function(resolve, reject) {
let r = Math.random();
if (r >= 0.5) {
resolve(r);
} else {
reject(r);
}
});
▪ To use the above promise, we provide two functions for the two outcomes and pass to the
promise then() method
▪ myPromise.then(
(v) => console.log(`Fulfilled for value ${v}`),
(v) => console.log(`Rejected for value ${v}`),
);
▪ Rejected event can also be handled by catch() method
▪ myPromise.catch(
(v) => console.log(`Rejected for value ${v}`)
);

19
19
RMIT Classification: Trusted

Promise (3)
▪ Promise objects also support finally() method. This method accepts a function that is called
when the promise is settled (either fulfilled or rejected)
▪ When a value is returned in a then() callback, that value is wrapped in a promise. So, you
can call then() on the next promise, and so on
▪ myPromise.then((v) => function1(v)).then((v) => function2(v)).then((v) =>
function3(v));
▪ Promise.all() static method takes an iterable of promises as input and returns a single
promise. This returned promise fulfills when all the input's promises fulfill, with an array of
the fulfillment values. It rejects when any of the input's promises rejects, with this first
rejection reason
▪ The static method Promise.any() has an opposite behavior
20
20
RMIT Classification: Trusted

async and await

▪ An async function returns a promise. The returned value is the promise value when it is
fulfilled
▪ Inside an async function, the await keyword is permitted
▪ The await keyword makes the function pause and wait for a resolved promise before it
continues
▪ Let’s say you want to authenticate a user. The following steps are required
• Step 1: connect to a DB
• Step 2: retrieve data from a table
• Step 3: compare the retrieved data with the user provided data
▪ As Step 1 and Step 2 interact with an external system, they return promises. So, your code
is something like
• connect(dbConfig).then((ok) => retrieveData()).then((data) => compareData(data));

21
21
RMIT Classification: Trusted

async and await (2)

▪ Instead of doing as before, we can use await keyword inside an async function
▪ The steps now become
• async function validate() {
const connection = await connect(dbConfig);
const data = await retrieveData();
compareData(data);
}
▪ await can only be used inside an async function
▪ Using await can make asynchronous programming behaves like synchronous programming
▪ Example: the fetch() API
• The fetch() API retrieve a resource
• The return value of fetch() is a promise that resolves to a Response object
▪ The public API endpoint https://catfact.ninja/fact returns a random fact about cat. Let's use
fetch() to get some interesting facts about cats

22
22
RMIT Classification: Trusted

fetch() API example


▪ With the response object, we call json() method to get the body text as JSON. This method
also returns a promise that resolves to JSON data
▪ Example:
▪ fetch('https://catfact.ninja/fact').then(res => res.json()).then(data =>
console.log(data.fact));

23
23
RMIT Classification: Trusted

fetch() API troubleshooting


▪ Why we got errors here?

24
24
RMIT Classification: Trusted

Using async and await


▪ We can create an async function and use await to accomplish the same objective
▪ async function getCatFact() {
const response = await fetch('https://catfact.ninja/fact’);
const data = await response.json();
console.log(data.fact);
}
▪ getCatFact();
▪ getCatFact();

25
25
RMIT Classification: Trusted

Workers (*)
▪ In a single-threaded program, all statements must be executed one by one
▪ Workers allow some tasks to run in a different thread
▪ Once JavaScript starts a task in a new thread, it runs the next task immediately
▪ Multiple threads can access to the same shared data => may lead to unexpected results
▪ As a result, the main thread and worker threads should not share data. They should
communicate by sending messages to each other
▪ This example from MDN Web Docs illustrate the use of web workers and how to
communicate between the main thread and worker threads
▪ The main components in the above example:
• generate.js: this code runs in a worker thread. It listens for the event "generate" from the main thread, then
starts the function generatePrimes(). Once the execution of the function generatePrimes() finishes, it sends a
message to the main thread by calling postMessage() method
• main.js: this code starts a new worker thread with the code given in the generate.js file. It calls the
postMessage() method to send an event 'generate' to the worker. It also registers a listener for the event
'message', so it can receive the result sent back by the worker

26
26
RMIT Classification: Trusted

Worker example (*)


▪ Source: https://github.com/mdn/learning-area/blob/main/javascript/asynchronous/workers/finished/main.js

27
27
RMIT Classification: Trusted

Intro to TypeScript

• TypeScript is a statically typed superset of JavaScript developed by


Microsoft. It adds types and other features to help build robust and
maintainable applications, and compiles to plain JavaScript for universal
compatibility
• Installation
• Install NodeJS
• Install TypeScript globally: npm install -g typescript
• Develop a TypeScript program (e.g., test.ts)
• Compile the TypeScript program to a JavaScript program: tsc test.ts
• Run the JavaScript program using NodeJS: node test.js

28
28
RMIT Classification: Trusted

Hello, TypeScript

• Wrong types are detected at coding time (not run time)

• Compilation result

29
29
RMIT Classification: Trusted

ts-node

• You can also install ts-node, a TypeScript execution and REPL for NodeJS

• REPL (Read, Evaluate, Print, and Loop): let you input TypeScript code and get the result

immediately
• Installation: npm install -g ts-node

• Run TypeScript file directly: ts-node test.ts


• Start a TypeScript REPL

30
30
RMIT Classification: Trusted

Primitive types

• You can specify the types of the variables and constants

• If you don't specify the type, TypeScript infers the type automatically

• Union type: more than one type is allowed

• Literal types: let grade: 'HD' | 'DI' | 'CR' | 'PA' | 100 | 0;

31
31
RMIT Classification: Trusted

Array

• Array of numbers
• let nums: number[] = [1, 2, 3];
▪ Array of strings
• let names: string[] = ['Alice', 'Bob', 'Carol'];
▪ Array of objects
• let students: object[] = [
{id: 123, name: 'Alice', major: 'IT', GPA: 3.0},
{id: 456, major: 'SE', GPA: 3.2},
];

▪ Array of any
• let arr: any[] = [1, 'two', true, 'four'];
▪ Array of union types
• let arr: (string | number)[] = [1, 'two', 3, 'four'];

32
32
RMIT Classification: Trusted

Tuple, Object, and Interface

• Tuples: arrays with fixed sizes and data types


• let product: [number, string, number];
• product = [123, 'Laptop', 333.44];
▪ Object

▪ Use interface for multiple objects with the same


properties and types

33
33
RMIT Classification: Trusted

Object function properties

• Functions can be properties of object

• Functions in TypeScript have arguments' types

as well as return type


• function add(n1: number, n2: number): number {
return n1 + n2;
}
• let add = (n1: number, n2: number): number => {
return n1 + n2;
}

• If a function returns nothing: void

34
34
RMIT Classification: Trusted

Class

• TypeScript also supports class,

constructor, method, setter and


getter, inheritance, visibility, static
and instance properties, etc.
• More detailed information about
TypeScript classes

35
35
RMIT Classification: Trusted

More features

• Generics: create components that can work with many types

• More information about generics

• Enums: collection of related values (number, string, named constants)

• More information about enums

• TypeScript Cheat Sheets

• https://www.typescriptlang.org/cheatsheets/

36
36
RMIT Classification: Trusted


Thank you
Tri Dang
[email protected]

37

You might also like