2 ServerSideJS
2 ServerSideJS
2
JavaScript
3
Classes in JavaScript
4
Class
- Classes are one of the features introduced in
the ES6 version of JavaScript
- A class is a blueprint for the object. You can create an
object from the class
- The class as a sketch (prototype) of a house.
+ Contains all the details about the floors, doors, windows,
etc.
+ Based on these descriptions, you build the house.
House is the object
5
Public methods
constructor is optional,
class ClassName { called automatically each
constructor(params) { time an object is created
...
}
Parameters for the
methodName() {
... constructor and methods are
} defined in the same they are
methodName() { for global functions
...
}
} You do not use the function
keyword to define methods
6
Public methods
class ClassName {
constructor(params) {
...
} Within the class, you must
methodOne() { always refer to other methods
[Link]();
}
in the class with the this.
methodTwo() {
prefix
...
}
}
7
Public fields
class ClassName {
fieldName; // Optional
constructor(params) {
[Link] = fieldValue;
[Link] = fieldValue;
}
methodName() {
[Link] = fieldValue;
}
}
class ClassName {
constructor(params) {
[Link] = someParam;
}
methodName() {
const someValue = [Link];
}
}
Within the class, you must always refer to fields with the
this. prefix
9
Private fields/methods
class ClassName {
#privateField // Required
constructor(params) {
this.#privateField = fieldValue;
[Link] = fieldValue;
}
#privateMethodName() {
this.#privateField = fieldValue;
}
}
10
Instantiation
class SomeClass {
...
someMethod() { … }
}
11
First-class functions
12
First-class functions
(This is also called having first-class functions, i.e. functions in JavaScript are
"first-class" because they are treated like any other variable/object)
13
First-class functions
(This is also called having first-class functions, i.e. functions in JavaScript are
"first-class" because they are treated like any other variable/object)
???
14
First-class functions
(This is also called having first-class functions, i.e. functions in JavaScript are
"first-class" because they are treated like any other variable/object)
What is code?
- A list of instructions your computer can execute
- Each line of code is a statement
What is a function?
- A labeled group of statements
- The statements in a function are executed when the
function is invoked
What is a variable?
- A labeled piece of data
16
Objects in JS
const bear = {
name: 'Ice Bear',
hobbies: ['knitting', 'cooking', 'dancing']
};
17
Back to the veeeeery basics
What is code?
- A list of instructions your computer can execute
- Each line of code is a statement
What is a function?
- A labeled group of statements
- The statements in a function are executed when the
function is invoked
function myFunction(params) {
}
19
Function variables
function myFunction(params) {
}
21
In the interpreter's memory:
const x = 15;
let y = true;
22
In the interpreter's memory:
x 15
const x = 15;
let y = true;
23
In the interpreter's memory:
x 15
24
In the interpreter's memory:
x 15
27
Function properties
[Link]();
greeting();
Important distinction:
- Function, the executable code
- A group of instructions to the computer
const bear = {
name: 'Ice Bear',
hobbies: ['knitting', 'cooking', 'dancing']
};
bear(); // error!
30
Function Objects vs Objects
function sayHello() {
[Link]('Ice Bear says hello');
}
const bear = {
name: 'Ice Bear',
hobbies: ['knitting', 'cooking', 'dancing'],
greeting: sayHello
};
[Link]();
function sayHello() {
[Link]('Ice Bear says hello');
}
const bear = {
name: 'Ice Bear',
hobbies: ['knitting', 'cooking', 'dancing'],
greeting: sayHello
};
[Link]();
33
[Link]
- Used to find the index of the first element in an array that
satisfies a given testing function. Returns -1 if no match is
found
- Syntax:
[Link](function(currentValue, index, arr), thisValue)
Parameter Description
function() Required. A function to be run for each array element.
currentValue Required. The value of the current element.
Index Optional. The index of the current element.
Arr Optional. The array of the current element.
thisValue Optional. Default undefined. A value passed to the
function as its this value.
34
[Link]
const flavors =
['vanilla', 'chocolate', 'strawberry', 'green tea'];
function isStrawberry(element) {
return element === 'strawberry';
}
35
[Link]
const flavors =
['vanilla', 'chocolate', 'strawberry', 'green tea'];
function isStrawberry(element) {
return element === 'strawberry';
}
36
[Link]
const flavors =
['vanilla', 'chocolate', 'strawberry', 'green tea'];
37
[Link]
const flavors =
['vanilla', 'chocolate', 'strawberry', 'green tea'];
function isStrawberry(element) {
return element === 'strawberry';
}
38
[Link]
const flavors =
['vanilla', 'chocolate', 'strawberry', 'green tea'];
39
[Link]
const flavors =
['vanilla', 'chocolate', 'strawberry', 'green tea'];
function isStrawberry(element) {
return element === 'strawberry';
}
40
[Link]
const flavors =
['vanilla', 'chocolate', 'strawberry', 'green tea'];
41
[Link]
const flavors =
['vanilla', 'chocolate', 'strawberry', 'green tea'];
function isStrawberry(element) {
return element === 'strawberry';
}
43
Anonymous functions
44
Anonymous functions
45
Arrow functions
46
Arrow functions
47
Concise arrow functions
We can use the concise version of the arrow function:
- You can omit the parentheses if there is only one
parameter
- You can omit the curly braces if there's only one
statement in the function, and it's a return statement
const index = [Link](
(element) => { return element === 'strawberry'; });
[Link]
48
Arrow functions and this keyword
const obj = {
i: 10,
b: () => [Link](this.i, this),
c: function() {
[Link](this.i, this);
}
};
obj.b(); // undefined {}
obj.c(); // 10 { i: 10, b: [Function: b], … } 49
Case-insensitive search
If we wanted to make this case insensitive, we could do:
const index = [Link](
element => [Link]() === 'strawberry');
51
[Link]
E.g., Map an array of objects to an array of strings:
const persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
[Link]([Link]((p) => {
return [[Link], [Link]].join(" ");
}));
52
[Link]
- Executes a reducer function on each element of the array and
returns a single output value. Syntax:
[Link](function(total, currentValue, currentIndex, arr), initialValue)
Parameter Description
function() Required. A function to be run for each element in the array.
Reducer function parameters:
total Required. The initialValue, or the previously returned value of the function.
currentValue Required. The value of the current element.
currentIndex Optional. The index of the current element.
arr Optional. The array the current element belongs to.
initialValue Optional. A value to be passed to the function as the initial value.
Note: - Normally, array element 0 is used as initial value, and the iteration starts
from array element 1.
- If an initial value is supplied, this is used, and the iteration starts from
array element 0
53
[Link]
E.g., Find sum of elements in an array:
const numbers = [ 1, 2, 5, 3, 6, 7 ];
const sum = [Link](
(acc, num) => acc + num,
0 // Init value for acc
);
[Link](sum);
54
Currying
55
Currying
Change a function having multiple arguments into a sequence of
functions with a single argument.
Ex: function add(a, b) function curryAdd(a)
{ return a + b; } { return function(b)
{ return a + b; } }
56
Currying
Recall: [Link] Example
const flavors =
['vanilla', 'chocolate', 'strawberry', 'green tea'];
function isStrawberry(element) {
return element === 'strawberry';
}
const indexOfStrawberry = [Link](isStrawberry);
const flavors =
['vanilla', 'chocolate', 'strawberry', 'green tea'];
function isFlavor(element) {
// ERROR: flavor is undefined!
return element === flavor;
}
const flavors =
['vanilla', 'chocolate', 'strawberry', 'green tea'];
function createFlavorTest(flavor) {
function isFlavor(element) {
return element === flavor;
}
return isFlavor;
}
const isStrawberry = createFlavorTest('strawberry');
const indexOfFlavor = [Link](isStrawberry);
const flavors =
['vanilla', 'chocolate', 'strawberry', 'green tea'];
function createFlavorTest(flavor) {
function isFlavor(element) {
return element === flavor;
}
return isFlavor;
}
const isStrawberry = createFlavorTest('strawberry');
const indexOfFlavor = [Link](isStrawberry);
63
Promises and .then()
A Promise:
- An object representing the eventually result of an
asynchronous operation
- Has a then() method that lets you attach functions to
execute onSuccess or onError
- Allows you to build chains of asynchronous results
Promises are one way to deal with asynchronous code, without getting stuck in callback hell.
64
Promise’s constructor syntax
66
Promise’s constructor syntax
68
Promise’s constructor syntax
69
Promise’s constructor syntax
70
Promise: A consumer function
● A consumer function (that uses an outcome of the promise)
should get notified when the executor function is done with
either resolving (success) or rejecting (error).
71
Promise: A consumer function
promise
.then((result) => {[Link](result);})
.catch((error) => {[Link](error);});
72
Promise: A consumer function
73
Promise: Fetch API
Không cần
thiết nếu dùng
npm install node-fetch@2 node v18.x
function onSuccess(response) { … }
function onFail(error) { … }
fetch(url).then(onSuccess, onFail);
74
Promise : Fetch API
fetch(url).then(onSuccess, onFail);
75
Promise: Fetch API
fetch(url).then(onSuccess, onFail);
76
Promise: Fetch API
78
Promise chaining
79
Promise chaining
You can return a promise from a .then() handler method. You will go
for it when you have to initiate an async call based on a response
from a previous async call.
80
Error handling
You can throw an error from the .then() handler. If you have a .catch()
method down the chain, it will handle that error. If we don't handle
the error, an unhandledrejection event takes place.
fetch(url)
.then(onSuccess)
.catch(onFail);
81
.then() .then().catch()
Error handling
82
Error handling
You can rethrow from the .catch() handler to handle the error later. In
this case, the control will go to the next closest .catch() handler.
83
[Link](iterable)
[Link]():
₋ Returns a single Promise that resolves to an array of the
results of the input promises
₋ It rejects immediately upon any of the input promises
rejecting
84
[Link](iterable)
85
async/await
86
Asynchronous fetch()
function onJsonReady(json) {
[Link](json);
}
The usual
function onResponse(response) {
asynchronous return [Link]();
fetch() looks like }
this:
fetch(url)
.then(onResponse)
.then(onJsonReady);
87
Synchronous fetch()?
A hypothetical synchronous fetch() might look like this:
88
async / await
89
async / await
92
async functions
96
async functions
97
async functions
99
async functions
100
async functions
101
async functions
102
async functions
If there are other events and we had a event handler for it,
JavaScript will continue executing those events
103
async functions
104
Recall: fetch() resolution
function onResponse(response) {
return [Link]();
}
fetch(url)
.then(onResponse);
The value of the await expression is the value that the Promise
resolves to, in this case response
106
async functions
107
async functions
If there are other events and we had a event handler for it,
JavaScript will continue executing those events
109
async functions
110
Recall: json() resolution
function onJsonReady(jsObj) {
Normally when json()
[Link](jsObj);
} finishes, it executes the
function onResponse(response) { onJsonReady callback,
return [Link](); whose parameter will
} be jsObj
fetch(url)
.then(onResponse)
.then(onJsonReady);
In Promise-speak:
- The return value of json() is a Promise that resolves to the
jsObj object 111
async functions
The value of the await expression is the value that the Promise
resolves to, in this case json
112
async functions
113
async functions
114
async functions
Note that the JS execution does *not* return back to the call
site, since the JS execution already did that when we saw the
first await expression
115
Returning from async
116
Returning from async
A: async functions must always return a Promise
117
Returning from async
function loadJsonDone(value) {
[Link]('loadJson complete!');
[Link]('value: ' + value); // value: true
}
119
Error handling with async/await
121
To get the return value from a
function in JavaScript
It depends on the function in question (check its docs)
// funct is synchronous
const retValue = funct();
129
JavaScript Object Notation
130
JavaScript Object Notation
131
[Link]()
const bear = {
name: 'Ice Bear',
hobbies: ['knitting', 'cooking', 'dancing']
};
132
[Link]()
133
Why JSON?
134
JSON
135
Some other features/syntax
136
Destructuring arrays/objects
When you are destructuring an object, the
name of the variables should match the
name of the properties of the object
otherwise, the destructuring will not work
let [a, b] = [ 1, 2, 3, 4 ]; and the value of the variable would
be undefined
[Link](a); // 1
[Link](b); // 2
137
Alias variables
const hero = {
name: 'Batman'
};
// Object destructuring:
const { name: heroName } = hero;
[Link](heroName); // 'Batman'
138
Dynamic property names
const x = 'name';
const a = { [x]: 'Batman' }
[Link]([Link]); // 'Batman'
[Link](a[x]); // 'Batman'
140
Spread operator (…)
Operator (...) allows us to quickly copy all or
part of an existing array or object into another
array or object
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];
arr1 = [0, 1, 2, 3, 4, 5]
Notice the properties that did not match were combined, but the property that did match,
color, was overwritten by the last object that was passed, mergedObj. The resulting foo is
now ‘baz’.
142
Rest operator (…)
const numbers = [1, 2, 3];
const [ first, ...restOfTheNumbers ] = numbers;
=> [ first, ...restOfTheNumbers ] = [1,2,3]
const [firstletter, ...restOfTheLetters ] = 'webdev';
=> [firstletter, ...restOfTheLetters ] = [ 'w', 'e',
'b', 'd', 'e', 'v' ]
const details = { firstName: 'Code',lastName:
'Burst',age: 22};
144
The need for modules
145
The need for modules
146
Immediately Invoked Function
Expression (IIFE)
[Link](); 147
CommonJS modules
• require(path/to/file)
• require(path/to/folder): [Link] file in the folder
will be used (for nodejs)
148
CommonJS modules
// [Link]
const { PI } = Math;
[Link] = (r) => PI * r ** 2;
[Link] = (r) => 2 * PI * r;
// [Link]
const circle = require('./[Link]');
[Link](`The area of a circle of radius 4 is
${[Link](4)}`);
149
CommonJS modules
// [Link]
class Square {
constructor(width) { [Link] = width; }
area() { return [Link] ** 2; }
};
[Link] = Square;
// [Link]
const Square = require('./[Link]');
const mySquare = new Square(2);
[Link](`The area of mySquare is
${[Link]()}`); 150
ECMAScript modules
// [Link]
// import named exports within curly braces with
// the same name
import circle, { area, circumference as c }
from './[Link]';
// or import everything
import * as circle from './[Link]';
// [Link] to access the default export (if any)
153
Module bundling
The process of stitching together a group of modules
(and their dependencies) into a single file (or group of
files) in the correct order*
• Usually involve some optimizations (i.e., removing
spaces to reduce file size)
154
*[Link]