The document provides an overview of various JavaScript and TypeScript features including:
1. Template strings, let/const, property shorthand, destructuring, spread operators, arrow functions, optional chaining, named exports, default exports, fetch, axios, async/await, and classes.
2. TypeScript setup instructions, primitive data types, any/unknown, literal types, arrays, enums, interfaces, extending interfaces, readonly/optional properties, type aliases, function types, and union/intersection types.
3. Examples are provided to demonstrate many of these features such as mapping arrays, filtering arrays, finding values in arrays, immutable data structures, and more.
2. Babel Coder
TEMPLATE
Template String
var myStr1 = 'Hello World'
var myStr2 = "Hello World"
var myStr3 = "HellonWorld"
var myStr4 = `
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
`
var myStr5 = `${myStr1} Krub`
3. Babel Coder
LET AND CONST
function foo() {
let x = 1
x = 2
}
foo()
function foo() {
const x = 1
x = 2
}
foo()
5. Babel Coder
DESTRUCTURING
let person = {
age: 24,
gender: 'male',
name: {
fi
rstName: '
fi
rstName',
lastName: 'lastName'
}
}
let age = person.age
let gender = person.gender
let name = person.name
let
fi
rstName = name.
fi
rstName
let lastName = name.lastName
let { age, gender, name } = person
let {
fi
rstName, lastName } = name
let { age, gender, name: {
fi
rstName, lastName } } = person
8. Babel Coder
ARROW FUNCTION
function foo(a) {
return a + 1
}
const foo = (a) => {
return a + 1
}
const foo = a => {
return a + 1
}
const foo = a => a + 1
const foo = a => let b = a + 1 Must be expression
10. ES MODULE - NAMED EXPORTS
export const DEFAULT_COLOR = 'white'
export function walk() {
console.log('Walking...')
}
{
DEFAULT_COLOR: 'white',
walk() {
console.log('Walking...')
}
}
dog.js
main.js
syntax: 1
import * as lib from './dog.js'
lib.DEFAULT_COLOR // white
lib.walk() // Walking...
main.js
syntax: 2
import { DEFAULT_COLOR, walk } from './dog.js'
11. ES MODULE - DEFAULT EXPORT
circle.js
main.js
syntax
export default class Circle {
area() {
}
}
import Circle from './circle.js'
12. ES MODULE - BOTH
circle.js
export const PI = 3.14
export default class Circle {
area() {
}
}
main.js
syntax
import Circle, { PI } from './circle.js'
17. EXAMPLE 1
Fetch content from URL: https://jsonplaceholder.typicode.com/todos
import axios from 'axios'
async function fetchPosts() {
const res =await axios.get(URL)
console.log(res.data)
console.log(res.status) // 200
}
fetchPosts()
HTTP GET HTTP POST
import axios from 'axios'
async function createPost() {
const res =await axios.post(
URL, { title: 'Test', completed: true })
console.log(res.status) // 201
}
createPost()
18. WHAT IS FUNCTIONAL PROGRAMMING
• Functional Programming is a programming paradigm.
• It treats computation as the evaluation of mathematical functions.
• Avoid changing state.
• Eliminating side effects of function calls.
• Declarative Style
30. Babel Coder
ANY AND UNKNOWN
function next(num: number) {
return num + 1;
}
let num: any = 10;
num = 'hello';
next(num);
num.toFixed(2);
let num: unknown = 10;
num = 'hello';
// Argument of type 'unknown' is not assignable to parameter of type 'number'.
next(num);
// Object is of type 'unknown'.
num.toFixed(2);
const num: unknown = 10;
next(num);
if (typeof num === 'number') {
next(num);
}
31. Babel Coder
LITERAL TYPES
let str1: 'Hello' = 'Hello';
let str2: string = str1;
// Type 'string' is not assignable to type '"Hello"'.
str1 = str2;
let str1 = 'Hello'; // string
const str2 = 'Hello'; // Hello
function permission(role: 'Admin' | 'Moderator' | 'Editor') {
// do sth
}
permission('Admin');
let role = 'Editor';
// Argument of type 'string' is not assignable
// to parameter of type '"Admin" | "Moderator" | "Editor"'.
permission(role);
permission(role as 'Editor');
32. Babel Coder
ARRAY
let nums1: number[] = [1, 2, 3] // number[]
let nums2: Array<number> = [1, 2, 3] // number[]
let nums3 = [1, 2, 3] // number[]
const nums4 = [1, 2, 3] // number[]
const nums5: readonly number[] = [1, 2, 3] // readonly number[]
const nums6: ReadonlyArray<number> = [1, 2, 3] // readonly number[]
const nums7 = nums6 as number[]; // number[]
const foo: string[] = []; // OK
const a: never[] = []; // OK
const b: never[] = [1, 2]; // Type 'number' is not assignable to type 'never'
33. Babel Coder
ENUM
enum Role {
Admin,
Moderator,
Editor,
}
const myRole: Role = Role.Admin; // 0
Role[0]; // Admin
Role.Admin // 0
enum Role {
Admin,
Moderator,
Editor,
}
enum Role {
Admin = 'Admin',
Moderator = 'Moderator',
Editor = 'Editor',
}
Role.Admin; // Admin
34. Babel Coder
INTERFACES
let person; // any
person = {
name: 'Somchai',
age: 24,
gender: 'male',
};
interface Person {
name: string;
age: number;
gender: string;
}
let person: Person;
person = {
name: 'Somchai',
age: 24,
gender: 'male',
};
// Property 'gender' is missing in type
// ‘{ name: string; age: number; }'
// but required in type 'Person'.
const person: Person = {
name: 'Somchai',
age: 24,
};
const person: Person = {
name: 'Somchai',
age: 24,
gender: 'male',
};
36. Babel Coder
READONLY AND OPTIONAL PROPERTIES
interface Person {
fi
rstName: string;
lastName: string;
middleName?: string;
readonly gender: 'Male' | 'Female';
}
let somchai: Person = {
fi
rstName: 'Somchai',
lastName: 'Haha',
gender: 'Male',
};
// Cannot assign to 'gender' because
// it is a read-only property.
somchai.gender = 'Female';
37. Babel Coder
TYPE ALIAS
interface Person {
name: string;
age: number;
gender: string;
}
type Person = {
name: string;
age: number;
gender: string;
};
interface Website {
url: string;
}
interface Article {
title: string;
content: string;
}
interface BlogPost extends Website, Article {
view: number;
}
type Website = {
url: string;
};
type Article = {
title: string;
content: string;
};
type BlogPost = Website &
Article & {
view: number;
};
38. Babel Coder
FUNCTION TYPES
function getFullName(
fi
rstName, lastName) {
return `${
fi
rstName} ${lastName}`;
}
function getFullName( fi
rstName: string, lastName: string): string {
return `${
fi
rstName} ${lastName}`;
}
const getFullName = function (
fi
rstName: string, lastName: string): string {
return `${
fi
rstName} ${lastName}`;
};
39. Babel Coder
FUNCTION TYPES
const getFullName = (
fi
rstName, lastName) => {
return `${
fi
rstName} ${lastName}`;
};
const getFullName = ( fi
rstName: string, lastName: string): string => {
return `${
fi
rstName} ${lastName}`;
};
type GetFullNameFn = (
fi
rstName: string, lastName: string) => string;
const getFullName: GetFullNameFn = (
fi
rstName, lastName) => {
return `${
fi
rstName} ${lastName}`;
};
47. Babel Coder
KEYWORD NEW
class Person {
constructor() {}
}
function get<T>(ctor: Factory<T>) {
return new ctor();
}
// const person: Person
const person = get(Person);
interface Factory<T> {
new (...args: any[]): T;
}
// OR
type Factory<T> = new (...args: any[]) => T;
51. Babel Coder
RECORD
type MyRecord<T extends string | number | symbol, U> = {
[K in T]: U;
};
type keys = 'name' | 'address';
// type MyPerson = {
// name: string;
// address: string;
// }
type MyPerson = MyRecord<keys, string>;
type Person = Record<keys, string>;
52. Babel Coder
PICK AND OMIT
type MyPick<T, K extends keyof T> = {
[P in K]: T[P];
};
type Person = {
name: string;
age: number;
address: string;
};
// type NameAndAge = {
// name: string;
// age: number;
// }
type MyNameAndAge = MyPick<Person, 'name' | 'age'>;
type NameAndAge = Pick<Person, 'name' | 'age'>;
type MyOmit<T, K extends string | number | symbol> = Pick<
T,
Exclude<keyof T, K>
>;
type Person = {
name: string;
age: number;
address: string;
};
// type MyAddress = {
// address: string;
// }
type MyAddress = MyOmit<Person, 'name' | 'age'>;
type Address = Omit<Person, 'name' | 'age'>;
53. Babel Coder
REQUIRED AND PARTIAL
type MyPartial<T> = {
[K in keyof T]?: T[K];
};
type Person = {
name: string;
age: number;
address: string;
};
// type MyPartialPerson = {
// name?: string | unde
fi
ned;
// age?: number | unde
fi
ned;
// address?: string | unde
fi
ned;
// }
type MyPartialPerson = MyPartial<Person>;
type PartialPerson = Partial<Person>;
type MyRequired<T> = {
[K in keyof T]-?: T[K];
};
type Person = {
name: string;
age: number;
address: string;
};
// type MyRequiredPerson = {
// name: string;
// age: number;
// address: string;
// }
type MyRequiredPerson = MyRequired<Person>;
type RequiredPerson = Required<Person>;
54. Babel Coder
READONLY
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
type Person = {
name: string;
age: number;
address: string;
};
// type MyReadOnlyPerson = {
// readonly name: string;
// readonly age: number;
// readonly address: string;
// }
type MyReadOnlyPerson = MyReadonly<Person>;
type ReadOnlyPerson = Readonly<Person>;
56. Babel Coder
DEFINITELY TYPED
// Could not
fi
nd a declaration
fi
le for module 'lodash'.
import lodash from 'lodash';
yarn add @types/lodash
yarn add @types/absinthe__socket
57. Babel Coder
A JAVASCRIPT LIBRARY
FOR BUILDING USER INTERFACES
Declarative
Component-Based
Learn Once, Write Anywhere
61. Babel Coder
COMPOSITION
App
function App() {
return (
<>
<SearchForm></SearchForm>
<SearchResults></SearchResults>
</>
)
}
function SearchForm() {
return <div>SearchForm</div>
}
function SearchResults() {
return <div>SearchResults</div>
}
SearchForm
SearchResults
62. Babel Coder
STATE
App
import React, { useState } from 'react'
function App() {
const [titles, setTitles] = useState(initialTitles)
return (
<>
<SearchForm></SearchForm>
<SearchResults></SearchResults>
</>
)
}
useState returns a pair: the current state value
and a function that lets you update it.
The only argument to useState is the initial state.
const initialTitles = [
'Reactive Programming
คื
ออะไร',
'เป
รี
ยบเ
ที
ยบ React, Vue และ Angular',
'Server Rendering'
]
70. Babel Coder
REACT HOOKS
Hooks are functions that let you “hook into” React state and lifecycle features from function
components.
RULES OF HOOKS
• Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
• Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions
(except custom hooks).
74. Babel Coder
MANAGE MUTABLE REF OBJECT
useRef returns a mutable ref object whose .current property is initialized to the passed argument
(initialValue). The returned object will persist for the full lifetime of the component.
WHEN TO USE REF
• Managing focus, text selection, or media playback.
• Integrating with third-party DOM libraries.
• Triggering imperative animations.
75. Babel Coder
REF TO ELEMENT
function App() {
const inputEl = useRef(null)
return (
<>
<input type="text" ref={inputEl} />
<button onClick={() => inputEl.current.focus()}>Focus</button>
</>
)
}
76. Babel Coder
MUTABLE OBJECT
function App() {
const counter = useRef(0)
const increase = () => {
counter.current += 1
console.log(counter.current)
}
return (
<>
<div>{counter.current}</div>
<button onClick={increase}>Focus</button>
</>
)
}
Changed
Unchanged
• A ref created with useRef will be created only when
the component has been mounted and preserved
during the full lifecycle.
• Refs can be used for accessing DOM nodes or React
elements, and for keeping mutable variables (like
instance variables in class components).
• Updating a ref is a side effect so it should be done
only inside an useEffect (or useLayoutEffect) or
inside an event handler.
78. Babel Coder
HOOKS AND LIFECYCLE
Mounting Updating Unmounting
render
React updates DOM and ref
Layout Cleanup
Layout Effect
Effect Cleanup
Effect
Render Phase
Pure, no side e
ff
ect. May be paused,
aborted or restarted by React.
Reconciliation Phase
Handled by React
Layout Phase
Can work with DOM,
but blocks the rendering
Commit Phase
Can work with DOM,
run side e
ff
ects, schedule updates
87. Babel Coder
RESTFUL
• Stands for “Representational State Transfer”
• RESTful Web Services are one way of providing interoperability between computer systems on
the Internet.
96. Babel Coder
HTTP STATUS CODES
CODE STATUS
1xx Informational responses
2xx Success
3xx Redirection
4xx Client Errors
5xx Server Errors
97. Babel Coder
HTTP STATUS CODES
CODE STATUS
200 OK
201 Created
204 No Content
401 Unauthorized
404 Not Found
405 Method Not Allowed
422 Unprocessable Entity
500 Internal Server Error
111. Babel Coder
AUTHENTICATION & AUTHORIZATION
Authentication
Articles
Authorization
Authentication is the process of ascertaining that somebody really is who he claims
to be.
Authorization refers to rules that determine who is allowed to do what.
113. Babel Coder
JSON WEB TOKEN
<HEADER>.<PAYLOAD>.<SIGNATURE>
JSON Web Token (JWT) is a JSON-based open standard (RFC 7519) for
creating access tokens that assert some number of claims.
Header
{
"alg": "HS256",
"typ": "JWT"
}
base64UrlEncode eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
Payload
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
base64UrlEncode
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI
6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9
Signature
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret
)
114. Babel Coder
PAYLOAD
Subject
sub This holds the identifier for the token
Issued At
iat When the token was issued (unix timestamp)
Expiry
exp The token expiry date (unix timestamp)
Issuer
iss The issuer of the token
115. Babel Coder
AUTH ROUTING
router.route('/auth');
router.post('/auth/sign-up', authController.register);
router.post('/auth/sign-in', authController.login);
router.get('/auth/pro
fi
le', authController.getPro
fi
le);
router.patch('/auth/pro
fi
le', authController.updatePro
fi
le);
router.post('/auth/refresh-token', authController.refreshToken);
router.delete('/auth/sign-out', authController.signOut);
121. Babel Coder
TESTING PYRAMID
Unit Tests
Integration Tests
UI Tests
ensure that modules which work well in isolation,
also play well together.
Unit testing
• focus on testing small units
• tested in isolation and independent of other units.
• Unit tests should be fast.
End-to-end testing is a methodology used to test whether
the
fl
ow of an application is performing
as designed from start to
fi
nish.
131. Babel Coder
TEST CASES
function multiply(a, b) {
return a * b
}
multiply.js
describe(‘multiply', () => {
it('multiplies two numbers correctly', () => {
expect(multiply(3, 2)).toBe(6)
})
})
multiply.test.js
Matchers
132. Babel Coder
TRUTHINESS
it('null', () => {
const n = null
expect(n).toBeNull()
expect(n).toBeDe
fi
ned()
expect(n).not.toBeUnde
fi
ned()
expect(n).not.toBeTruthy()
expect(n).toBeFalsy()
})
it('zero', () => {
const z = 0
expect(z).not.toBeNull()
expect(z).toBeDe
fi
ned()
expect(z).not.toBeUnde
fi
ned()
expect(z).not.toBeTruthy()
expect(z).toBeFalsy()
})
133. Babel Coder
NUMBERS
it('two plus two', () => {
const value = 2 + 2
expect(value).toBeGreaterThan(3)
expect(value).toBeGreaterThanOrEqual(3.5)
expect(value).toBeLessThan(5)
expect(value).toBeLessThanOrEqual(4.5)
// toBe and toEqual are equivalent for numbers
expect(value).toBe(4)
expect(value).toEqual(4)
})
it('adding
fl
oating point numbers', () => {
const value = 0.1 + 0.2
//expect(value).toBe(0.3) This won't work because of rounding error
expect(value).toBeCloseTo(0.3)
})
134. Babel Coder
STRINGS
it('there is no I in team', () => {
expect('team').not.toMatch(/I/)
})
it('but there is a "stop" in Christoph', () => {
expect('Christoph').toMatch(/stop/)
})
135. Babel Coder
ARRAYS
const programmingLangs = [
'JavaScript',
'Python',
'C/C++',
'Java',
'R'
]
it('the programming list has R on it', () => {
expect(programmingLangs).toContain('R')
})
136. Babel Coder
EXCEPTIONS
function compileAndroidCode() {
throw new Con
fi
gError('you are using the wrong JDK')
}
it('compiling android goes as expected', () => {
expect(compileAndroidCode).toThrow()
expect(compileAndroidCode).toThrow(Con
fi
gError)
// You can also use the exact error message or a regexp
expect(compileAndroidCode).toThrow('you are using the wrong JDK')
expect(compileAndroidCode).toThrow(/JDK/)
})