🐡

Typescript/Javascript/Node.js Advanced features

に公開

Difference between Typescript and Javascript

Typescript Javascript
Typing Static Dynamic
Compile Necessary Unnecessary
Error check Compile Runtime

Typescript

  • Superset of Javascript
  • Secure quality of code by static typing and error check in compile
  • Suitable for large-scale development

Primitive types

* number
* string
* boolean
* symbol
* bigint
* null
* undefined

Object types

  • object
  • array

Literal types

Any

Clean Code

Closure

Mechanism to access outer scoped variables from inner functions

function outerFunction() {
    let outerVariable = 'I am outer!';

    function innerFunction() {
        console.log(outerVariable);
    }

    return innerFunction;
}

let myFunction = outerFunction();
myFunction(); // Output: I am outer!
  • Useful for:
    • Encupslation for inner states
    • Avoid collisions of namespaces in global

Prototype

Javascript is prototype based programing language.
All Javascript objects are created from other objects and keeps it as a parent. You can access its properties via "prototype" property.

  • Useful for:
    • Contribute to save memory space
    • Inheritance by prototype chain

Prototype chain

Javascript object finds properties along the following flow.

  1. Search its own properties
  2. Change target to its prototype object and search the properties
  3. Repeat from 1.

higher-order function

A function which returns a fucntion or receive a fucntion as arguments.

  • Useful for:
    • Reuse function
    • Callback function
    • Currying

Aruguments

function applyOperation(x, y, operation) {
    return operation(x, y);
}

function add(x, y) {
    return x + y;
}

function subtract(x, y) {
    return x - y;
}

console.log(applyOperation(5, 3, add));        // output: 8
console.log(applyOperation(5, 3, subtract));   // output: 2

Return

function createMultiplier(factor) {
    return function(x) {
        return x * factor;
    };
}

const double = createMultiplier(2);
console.log(double(5));  // output: 10

const triple = createMultiplier(3);
console.log(triple(5));  // output: 15

this

A keyword to refer to the current object in the running code.
Very confusing since this means different target depending on the context.

method

this -> the object which function belongs to (obj).

const obj = {
    name: 'John',
    greet: function() {
        console.log('Hello, ' + this.name);
    }
};

obj.greet(); // Output: Hello, John

event hander

this -> event object (e).

const obj = {
    name: 'John',
    handleClick: function() {
        console.log('Hello, ' + this.name);
    }
};

// Refers to e.handleClick
document.getElementById('myButton').addEventListener('click', obj.handleClick);

Callback fucntion on setTimeout()

this -> global object

const obj = {
    name: 'John',
    greet: function() {
        setTimeout(function() {
            console.log('Hello, ' + this.name);
        }, 1000);
    }
};

// this.name = undefined
obj.greet();

Truthy/Falsy values

Best practice for null check

!= null
  • Best practice in the world
  • Can judge numeric 0 as true.
  • False values:
    • false
    • null
    • undefined
    • empty string
if (value != null) {
  // process
}
value itself
  • Best practice in the world
  • Attention to judge numeric 0 as false.
  • False values:
    • false
    • null
    • undefined
    • empty string
    • 0
if (value) {
  // process
}

Confusing evaluation

Be careful those patterns not to misevalutate

console.log(false == '0'); // true
console.log(null == undefined); // true
console.log(" \t\r\n" == 0); // true
console.log('' == 0); // true
if ({}) // true
if ([]) // true
console.log(isNaN(NaN));    // true

console.log(NaN == NaN);    // false
console.log(NaN === NaN);   // false

Modurization

A functionality to separate organise large amount of scripts.

  • default export: default item which is imported as default
    • Only single item per module
    • Can name anything when you import

export

// File Path: ./CharacterLib.js

// Export variables
export const CharacterList = ["Warrior", "Magician", "Monk"];

// Export function
export function getSerif(characterName, chapter, index) {
  return this.serifDict[characterName][chapter][index]
}

const AttackDamage = (attack, defence) => {
  return 
};

// Default export
default export AttackDamage;

// May export at once at the end of the file instead of adding `export` to each items
export { CharacterList, getSerif };

import

// Basic
import {CharacterList, getSerif} from `./CharacterLib.js`

// Alias
import {CharacterList as characters} from `./CharacterLib.js`

// Module Object
// usage) Chara.getSerif()
import * as Chara from "./CharacterLib.js";

// default export
// May name anything you like
// Not surround by {}
import AnyName from `./CharacterLib.js`

Currying

  • Transformation of a function call into multiple calls passing singular sequential parameters
  • f(a, b, c) -> f(a)(b)(c)
  • f(g(x)) -> F(f)(g)(x)
  • Useful for:
    • Function composition
    • Partial application of function
// Currying transformation
function curry(f) { 
  return function(g) {
    return function(x) {
      return f(g(x));
    };
  };
}

// May transform as arrow function
const curry = (f) => (g) => (x) => f(g(x));

// Usage
const square = (x) => {
  return x * x;
};
const halve = (x) => {
  return x / 2;
} 
const double = (x) => {
  return x + x;
}

// Reuse function composition
let halveMetric = curry(square)(halve);
let doubleMetric = curry(square)(double);

Console.log( halveMetric(2) ); // 1 
Console.log( doubleMetric(2) ); // 16

variable modifiers

modifier scope effect
const block immutable
let block mutable
var function mutable

High Performance

MicroTask/MacroTask

Priority for execution in a event loop: Microtask > Macrotask

Microtask

  • Short term async task
  • Queued into micro task queue
  • Execute all per a event loop
  • e.g )
    • Promise

Macrotask

  • Long term async task
  • Queued into macro task queue
    • Execute one per a event loop
  • e.g )
    • Timer process(setTimeout)
    • Event handling(keyboard, click)
    • Networking request(Ajax)

Promise

Object for async task.

Usage

  • States
    • pending: initial state, neither fulfilled nor rejected
    • fulfilled: meaning that the operation was completed successfully
    • rejected: meaning that the operation failed
  • Manual state change
    • resolve(): Successfully completed in status fulfilled
    • reject(): Failed in status rejected
  • Chain method
    • .then(): Callback in fulfilled
    • .catch(): Callback in rejected
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("foo");
  }, 300);
});

myPromise
  .then(handleFulfilledA, handleRejectedA)
  .catch(handleRejectedAny);

Confusing evaluation

Be careful when you use it with Macrotask* such as setTimeout() patterns

  • Priority: Promise > global context > Macrotask in Promise > then() > Macrotask
new Promise(function promise(resolve) {
  // 1st
  console.log('promise');
  // 3rd
  setTimeout(function task1() {
    console.log('macroTask1');
    resolve();
  });

// After executing resolve()
}).then(function job1() {
  // 4th
  console.log('job1');
})

// 2nd
console.log('global end')

// Output order:
// promise
// global end
// macroTask1
// job1

Javascript Engine

A software component to parse and execute. A part of JS runtime.

Steps

step input output
1 parse Javascript -> Token
2 interpretation Token -> AST
3 compile AST -> Byte code

Types

Company Browser Javascript Engine
Google Chrome V8
Mozilla Mozilla SpiderMonkey
Apple Safari JavascriptCore

Rendering Engine

step note
1 Download Download data from server
2 DOM Tree Parse HTML and Create DOM Tree
3 CSSOM Tree Parse CSS and Create CSSOM Tree
4 Scripting Execute Javascript and Modify DOM/CSSOM Tree
5 Rendering Tree Combine DOM/CSSOM Tree
6 Layout Caliculate accurate positions or size of nodes
7 Paint Determine the sequence for rendering objects
8 Composite Rasterize each layer and composite them
Cause Effect Solution
Parser Blocking Loading <script> for inline code or external JS File delays creating DOM tree delay scripting by defer or async attribute
Render Blocking Loading inline <style> or <link> for external CSS file delays creating Rendering tree async loading by rel="preload"

Types

Company Browser Rendering Engine
Google Chrome Blink
Mozilla Mozilla Gecko
Apple Safari Webkit

Webpack

A tool to bundle multiple javascript files into a file

  • JS files bundled into dist/main.js
  • Configure in webpack.config.js
  • Need loader to bundle non-JS file such as .scss
  • Useful for:
    • Optimising file transfer by reducing requests from browser

code splitting

Coming soon...

Collection

Security

CSRF

XSS

Click jacking

HTTP Security Headers

Discussion