0%

Position value

  1. static

    • default value
  2. relative

    • move relatively from static position
  3. absolute

  4. sticky

JavaScript

  • 웹 페이지의 동적인 부분을 담당한다.

ES6 (ECMAScript 2015)

  • 브라우저 호환성을 위해 트랜스컴파일러로 컴파일 됨
  • class
  • const & let
  • block scope
  • arrow function
  • promise
  • spread operator
  • template literal
    • ${expression} with `
  • destructuring
Screenshot 2021-04-10 at 15 08 48
  • let

    • 변하는 값을 할당할 때
    • 변수명은 lowerCamelCase
  • const

    • 변하지 않는 값을 할당할 때
    • 변수명은 SNAKE_CASE

hoisting (변수 할당 전에 접근 시)

  • var : undefined
  • let : reference error

Scope

  1. Function Scope
  • function 블록 내에서 유효
  • 함수 내부에 선언되면 지역변수
  • 외부에 선언되면 전역변수

지역변수

  • 함수 내부에 선언
  • 함수 내부에서만 접근 가능
  • 함수가 시작될 때 생성되고, 함수 context가 종료될 때 삭제됨

전역변수

  • 함수 외부에 선언
  • 어디에서나 접근 가능
  1. Block Scope
  • {} 가 있는 경우
    • if, switch 문…
Screenshot 2021-04-10 at 15 13 27
  • var a

  • 전역 변수

  • var b

    • 지역 변수

    • function scope

      • if문 밖에서도 접근 가능 (if문이 function 안에 있기 때문)

      var variables are function scope.

      : It means they are only available inside the function they’re created in, or if not created inside a function, they are ‘globally scoped.’

      globally scoped

      : returns undefined

  • let c

    • 지역 변수
    • block scope
      • if문 밖에서 접근 불가 (참조 불가능)

Hoisting

  • scope에 따라 선언할당 으로 구분됨
  • 변수의 선언문과 함수의 선언식을 유효 범위의 최상단으로 끌어올리는 것
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function hoisting() {
console.log(d);
console.log(e);

var d = "be";
let e = "sopt";

function f() {
console.log("28th");
}
}

hoisting();

👇

function hoisting() {
// 변수 선언문 (메모리 할당)
var d;
let e;
// 함수 선언식
function f() {
console.log("28th");
}

// 기존 식 순차적으로 실행
console.log(d); // undefined
console.log(e); // ReferenceError

d = "be";
e = "sopt";
}

hositing();
Screenshot 2021-04-10 at 15 15 15 Screenshot 2021-04-10 at 15 20 20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var g = "web";

function outer () {
console.log(g);
function inner () {
console.log(g);
var g = "part";
}
inner();
console.log(g);
}

outer();
console.log(g);

👇

var g;
function outer () {
function inner () {
var g;
console.log(g); // undefined
g = "part";
}
console.log(g); // web
inner();
console.log(g); // web
}
g = "web";
outer();
console.log(g); // web

원시 자료형

1
typeof == object
  • Boolean
  • Number
    • BigInt
  • String
    • `` 내부에${}` 변수 사용 가능
  • Symbol
    • 유일한 식별자
    • 내용이 같아도 변수가 다르면 다른 객체임
  • Null
    • 값이 존재하지 않음
    • 값을 알 수 없음
1
typeof == undefined
  • Undefined
    • 값이 할당되지 않음

객체 자료형

배열

1
2
3
4
5
6
7
8
9
10
11
const arr;

// 배열 생성
arr = [];
arr = new Array();

// 배열 길이
arr.length;

// 배열 참조
arr[i];
  • 배열의 각 요소의 타입이 모두 다를 수 있다
  • 배열의 index가 연속적이지 않아도 된다
    • 비어있는 index는 undefined 로 처리된다
method
  1. push
    • 배열의 맨 마지막 요소부터 접근
      • 마지막에 요소 추가
  2. pop
    • 배열의 맨 마지막 요소부터 접근
      • 마지막 요소 제거
  3. shift
    • 배열의 맨 처음 요소부터 접근
      • 처음 요소 제거 후 다음 요소부터 하나씩 왼쪽으로 옮김
    • 시간 복잡도 안 좋음
  4. unshift
    • 배열의 맨 처음 요소부터 접근
      • 처음에 요소 삽입 후 하나씩 오른쪽으로 옮김
    • 시간 복잡도 안 좋음
  5. length
  6. concat
    • 두 배열을 합친 새로운 배열 반환
  7. sort
    • 배열 요소들을 사전 기준 으로 순서대로 나열
  8. map
    • 요소에 하나씩 접근하여 함수의 내용을 적용한 뒤 새로운 배열 반환

JavaScript method

  • 반복문
Screenshot 2021-04-10 at 15 37 47
  1. for ... in

    • index 접근
  2. for ... of

    • element 접근
  3. forEach

    • index, element 모두 접근
    • (element, index) 순서 바꾸면 안 됨!
  • String 반복
1
2
// String의 `repeat` 함수
String.repeat(i)

함수

  • 일급 객체
    • 변수나 데이터 구조에 할당 가능
    • 다른 함수의 파라미터로 전달 가능
    • 반환 값으로 사용 가능
    • 런타임 시 생성 가능
  • () 를 이용하여 함수를 호출하지 않으면 실행되지 않음

사용하는 이유

  • 코드 재사용
    • 같은 함수에 다른 인자를 넣으면 다른 결과를 냄
선언
Screenshot 2021-04-10 at 16 04 05
  • 함수 선언문

  • 기명함수 표현식

    • 변수에 할당
      • hoisting에 영향을 받지 않음
    • 함수 이름 따로 선언
      • _name 형식

    잘 사용하지 않음

  • 익명함수 표현식

    가장 많이 사용!

    • 변수에 할당
      • hoisting에 영향을 받지 않음
    • 함수 이름 따로 지정하지 않음
화살표 함수
  • 익명함수 표현식을 간결하게 표현한 것
  • 매개변수가 하나면 소괄호 생략 가능
  • 함수 내부에 return 문만 있다면 return 생략 가능
매개변수와 인자
  • 매개변수 (parameter)
    • 함수 정의에 사용되는 변수
    • 함수가 실행되기 전까지는 값을 가지지 않음
  • 인자 (argument)
    • 함수를 호출할 때 전달하는 값
    • 함수에 적용되는 실질적인 값
반환 값 (return)
  • 함수 실행을 종료하고 함수 호출 지점으로 값을 반환함
  • 함수 내부에서 return이 실행될 경우, 이후 코드는 실행되지 않음
  • return이 지정되지 않은 경우는 undefined 반환
    • return undefined; 와 동일
좋은 함수 만들기
  • 하나의 함수는 하나의 기능
  • 함수명은 짧고 명확해야 하며, 동사로 시작
  • lowerCamelCase
  • arrow function으로 작성하는 것이 권장됨

Operator

Screenshot 2021-04-10 at 16 10 51

주로 === 이용할 것!

객체

Screenshot 2021-04-10 at 15 50 41
  • **property === (key , value) ** 쌍 1개

    • key: value,
  • value에는 어떤 것이든 올 수 있음

  • property 간에는 쉼표로 구분됨

  • method : property value로 함수가 오는 것

    • 사용 시 varName.methodName() 으로 호출
    • e.g. sayHi method

JSON (JavaScript Object Notation)

  • 객체 표현식

  • (key, value) 로 구성된 property들의 정렬되지 않은 집합

  • 서버-클라이언트 통신할 때 사용함

  • localStorage 등 웹 저장소에 저장할 때도 사용함

    • localStorage data is specific to the protocol of the document

      In particular, for a site loaded over HTTP (e.g., http://example.com), localStorage returns a different object than localStorage for the corresponding site loaded over HTTPS (e.g., https://example.com).

Screenshot 2021-04-10 at 16 15 50

동기와 비동기

JavaScript

  • synchronous

    Synchronous means that if you need to wait for something, then everything stops until the wait is over.

  • single thread

    Single threaded means that only one thing happens at a time.

  • Sync

    • 차례대로 실행
    1
    2
    3
    4
    5
    6
    7
    8
    9
    const getCoffee = (coffee) => { // coffee === null
    setTimeout(() => {
    coffee = "Ice Americano";
    }, 3000);
    console.log(coffee); // coffee === null
    };

    let coffee = null;
    getCoffee(coffee); // null
  • Async

    • 해당 코드가 끝날 때까지 다른 코드를 실행하지 않음
    1
    2
    3
    4
    5
    6
    7
    8
    9
    const getCoffee = (coffee) => { // coffee === null
    setTimeout(() => {
    coffee = "Ice Americano";
    console.log(coffee); // coffee = "Ice Americano"
    }, 3000);
    };

    let coffee = null;
    getCoffee(coffee); // Ice Americano

콜백 함수

  • 자바스크립트는 single thread 이기 때문에 효율성을 위해서 기본적으로 동기적 으로 처리함
    • 비동기적으로 처리할 시 waiting time이 무한대로 길어질 수도 있음
  • 비동기로 처리하기 위해서는 콜백 함수를 이용함
  • 다른 함수의 인자로 전달된 콜백함수는 특정 이벤트가 발생하면 호출됨
    • e.g. setTimeout
  • ❓다른 객체에게 “이벤트가 끝나면 알려달라”고 일을 맡기고, 해당 이벤트가 끝나면 해당 콜백함수를 실행함
Screenshot 2021-04-10 at 16 20 59
  • Asynchronous : setTimeout()에 모두 묶어버림

  • callback function : const second

콜백 지옥
  • 클린 코드를 위해 피해야 할 것!
    • if문 분기와 error handling을 어렵게 만듦
  1. 익명함수를 분리하여 기명함수로 작성하거나

  2. promise 와 같은 비동기 처리를 사용할 것

Promise

  • 자바스크립트 비동기 처리에 사용되는 객체

  • new Promise() 를 통해 선언, 인자는 (resolve, reject)

    • const promise = new Promise((res, rej) => {});
  • return 값은 resolve나 reject 내부의 메시지

  • resolve, reject 둘 중 하나만 실행

    • 둘 다 있다면 나중에 작성된 코드 무시
  • fetch 를 사용하여 실제 API를 호출하면 Promise 객체가 반환됨

  • response.json() 을 통해 response의 body를 JSON 객체로 변환함

    • 이 메소드의 실행 결과도 Promise
Promise의 3가지 상태
Screenshot 2021-04-15 at 20 43 45
  1. pending : 아직 비동기 처리가 완료되지 않음
  2. fulfilled : 비동기 처리가 완료되어 결과값이 반환됨
    • then 실행
    • then을 연속으로 사용할 수 있음
    • catch 이후에도 then 설정 가능
    • throw Error() 를 통해 에러가 발생하면 catch 실행
  3. rejected : 비동기 처리 중 오류가 발생함
    • catch 실행

finally 는 결과 상관 없이 실행됨

Async / Await

Screenshot 2021-04-10 at 16 31 05
  • await은 async 함수 안에서만 사용 가능
  • await은 결과가 resolve, reject이든 상관 없이 Promise가 끝날 때까지 기다림
  • then, catch 를 사용하지 않고 무조건 Promise 결과를 얻음

Notification

  1. Alert : 사용자가 확인을 누를 때까지 메시지를 보여줌

  2. Prompt : 사용자에게 값을 입력받음

    • 첫번째 인자는 notifying message

    • 두번째 인자는 default 값, 사용자가 취소를 누르면 null 리턴

  3. Confirm : 사용자에게 질문을 보여주고 true / false 리턴

async / defer

Screenshot 2021-04-10 at 16 36 52
  • async : script가 html의 영향을 받지 않을 때
    • e.g. DOM 조작 요소가 없을 때
    • HTML pausing해도 영향 없음
  • defer : script가 html의 영향을 받을 때
    • e.g. DOM 조작 요소가 있을 때
    • 일단 모두 로딩하고 reloading

API

Canvas

  • 애니메이션, 게임 그래픽, 사진 조작, 영상 처리 등 그래픽을 그리기 위한 방법
  • API이기 때문에 자바스크립트로 조작한다
1
2
3
<!- 넓이와 높이 지정해야 함 (css로 조정해도 됨) ->
<canvas id="canvas" width="500" height="500"></canvas>
<script src="canvas.js"></script>
1
2
3
4
// canvas element 가져오기
const canvas = document.getElementById("canvas");
// canvas의 context를 "2d"로 지정하기
const ctx = canvas.getContext("2d");
Screenshot 2021-04-10 at 16 43 28 Screenshot 2021-04-10 at 16 49 25
  • 모니터의 좌측 상단 : (0,0)
Screenshot 2021-04-10 at 16 50 03 Screenshot 2021-04-10 at 16 56 50 Screenshot 2021-04-10 at 16 52 04 Screenshot 2021-04-10 at 16 54 07 Screenshot 2021-04-10 at 16 54 43

Drag-and-Drop

  • 특정 element를 마우스로 끌어서 원하는 위치로 옮기는 HTML API
  • element의 위치를 바꾸거나, 파일을 업로드할 때 자주 사용함
1
2
3
4
5
6
<div class="bucket">
<img src="cat.png" id="cat" draggable="true" />
</div>
<div class="bucket"></div>
<div class="bucket"></div>
<div class="bucket"></div>
  • id 지정 후 draggable="true"
1
2
3
#cat {
z-index: 1;
}
  • z-index 설정
1
2
3
4
5
6
7
8
9
const buckets = document.querySelectorAll(".bucket");
const cat = document.getElementById("cat");

// 상자에 allowDrop(dragover), drop event 추가
buckets.forEach((bucket) => addEventListener("dragover", allowDrop));
buckets.forEach((bucket) => addEventListener("drop", drop));

// 고양이에 drag(dragstart) event 추가
cat.addEventListener("dragstart", drag);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function allowDrop(event) {
// 기본 동작 막기
event.preventDefault();
}

function drag(event) {
// 고양이 이미지의 id를 옮겨야하므로 유형은 "text", 데이터(cat)는 event.target.id
event.dataTransfer.setData("text", event.target.id);
}

function drop(event) {
event.preventDefault();
// 옮기려고 저장한 고양이 이미지의 id 가져오기
const imageID = event.dataTransfer.getData("text");
// 현재 이벤트가 발생한 요소(dropBox)의 하위 요소에 element를 추가하여 자식 노드(cat)로 만들기
event.target.appendChild(document.getElementById("imageID"));
}

Function Statement

  • hoisted to the top of the full lexical scope
    • can break conflicting scripts
    • it’s difficult to debug
  • named function is shown in the stack trace
    • easier to debug when error occurs in the function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
Function declarations are given two passes,
where the first lifts them to the top (hoisting),
allowing "out of order" usage
*/


doTheThing();

function doTheThing() {
console.log(`This is awesome number ${getAwesome()}`)
}

function getAwesome() {
return (+((Math.random() * 10000).toString().split('.')[0]))
}

Const Declaration

  • edge-case hoisting
  • declare a variable
    • gives it a block scope
    • stops the full hoisting
  • cannot be re-declared
    • throws exception if re-declared
    • easier to debug
  • won’t be caught until called
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
This shows that, because of block-scoping,
const function references must be invoked in-order
or else things will fail silently.
consts are added serially (in the order in which they appear)
and much of the body isn't declared when we first try to invoke or functions
*/


// use `getAwesome()`
const tryDoTheThing = () => {
console.log(`This is me trying to be awesome ${getAwesome()}`)
}


// "getAwesome is not defined", because it is referenced too early,
// before declaring `getAwesome()` function
tryDoTheThing()


const getAwesome = () => (+((Math.random() * 10000).toString().split('.')[0]))


const doTheThing = () => {
console.log(`This is awesome! ${getAwesome()}`)
}

doTheThing()

Responsive Web

Always Design for Mobile First

  • 데스크탑, 태블릿, 노트북, 스마트폰 등의 다양한 기기가 등장하면서 데스크탑의 화면에 최적화되어 있던 레이아웃을 각 기기의 화면 크기에 맞게 유동적으로 변동해야 하는 필요성이 대두됨
  • 내용은 동일하지만 최적화된 레이아웃 렌더링

반응형의 중요성

  1. 모바일 시장

  2. 더 나은 User eXperience

  3. 빠른 페이지 로딩 속도

  4. 효율적이고 cost-effective

    • 버전을 나누어 유지, 보수할 필요가 없음

종류

1) Responsive Layout (adaptive design)

  • media query 이용해 breakpoint 적용
  • 각 component가 px 으로 표현됨

2) Fluid Layout

  • 페이지의 크기에 따라 레이아웃의 크기도 변경됨
  • relative unit인 em 또는 % 으로 표현됨
  • time-consuming
  • 매번 testing 해야 함

3) Fluid-responsive Layout

  • responsivefluid 레이아웃의 결합

  • media querybreakpoints 이용

  • 더 자연스러운 레이아웃 변화

CSS Media Query (Fluid grid system)

@media rule

  • width and height of the viewport
  • width and height of the device
  • orientation (landscape / portrait)
  • resolution

Media Types

Value Description
all Default. Used for all media type devices
print Used for printers
screen Used for computer screens, tablets, smart-phones etc.
speech Used for screenreaders that “reads” the page out loud

Media Features

Value Description
max-height The maximum height of the display area, such as a browser window
min-width The minimum width of the display area, such as a browser window

css

1
2
3
@media not|only mediatype and (mediafeature and|or|not mediafeature) {
CSS-Code;
}

scss

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Media Query Mixins

// Mobile
@mixin mediaSm {
@media screen and (max-width: 500px) {
@content;
}
}

// Tablet
@mixin mediaMd {
@media screen and (max-width: 768px) {
@content;
}
}

// Desktop
@mixin mediaLg {
@media screen and (min-width: 769px) and (max-width: 1170px) {
@content;
}
}

// TV, etc.
@mixin mediaXl {
@media screen and (min-width: 1171px) {
@content;
}
}

html

1
2
3
<link rel="stylesheet" media="screen and (min-width: 900px)" href="widescreen.css">
<link rel="stylesheet" media="screen and (max-width: 600px)" href="smallscreen.css">
....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}
Reference

https://css-tricks.com/a-complete-guide-to-css-media-queries/

Objects and Data Structures

  1. Getter and Setter

    • JS는 인터페이스 / 타입 / 접근제어자 (Access Modifier) 을 가지고 있지 않음

    • Object property를 가져오는 것 이상 (e.g., modify) 의 action을 하고 싶을 때, 일일이 접근제어자를 불러 action을 취하지 않아도 됨

    • set action 시 validation을 추가하는 것이 좋음

    • internal representation을 encapsulating

    • get, set시 logging이나 error handling을 추가하는 것이 용이함

    • get 시 lazy load 속성을 추가할 수 있음

    Lazy loading

    • It’s a way to shorten the length of the critical rendering path, which translates into reduced page load times
    • getting the properties from a server
    1. identify resources as non-blocking (non-critical)
    2. load these only when needed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// bad
function makeBankAccount() {
// ...

return {
// ...
balance: 0
};
}

const account = makeBankAccount();
account.balance = 100;


// good
function makeBankAccount() {
// private으로 선언된 변수
let balance = 0;

// 아래 return을 통해 public으로 선언된 "getter"
function getBalance() {
return balance;
}

// 아래 return을 통해 public으로 선언된 "setter"
function setBalance(amount) {
// ... balance를 업데이트하기 전 검증로직
balance = amount;
}

return {
// ...
getBalance,
setBalance
};
}

const account = makeBankAccount();
account.setBalance(100);
  1. objects의 properties는 private로 만들기

    • closures
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    // bad
    const Employee = function(name) {
    this.name = name;
    };

    Employee.prototype.getName = function getName() {
    return this.name;
    };

    const employee = new Employee('John Doe');
    console.log(`Employee name: ${employee.getName()}`);
    // Employee name: John Doe
    delete employee.name;
    console.log(`Employee name: ${employee.getName()}`);
    // Employee name: undefined


    // good
    function makeEmployee(name) {
    return {
    getName() {
    return name;
    },
    };
    }

    const employee = makeEmployee('John Doe');
    console.log(`Employee name: ${employee.getName()}`);
    // Employee name: John Doe
    delete employee.name;
    console.log(`Employee name: ${employee.getName()}`);
    // Employee name: John Doe

Functions

  1. 함수 parameter / argument는 2개 이하

    함수 테스팅을 쉽게 만들어 주기 때문

    • 3개 이상인 경우: 통합하기

    • higher-level object의 경우 1개로 충분함

    • 객체를 생성하고 활용하기

      • 적은 boilerplate으로도 객체를 만들기 쉬우므로, argument가 많이 필요한 경우 객체를 생성해서 활용하기

      boilerplate : 변경 없이 계속 재사용할 수 있는 코드, 프로그램

      • Destructuring

        구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다.

        • function signature (argument, return type) 등을 통해 어떤 값이 전달되고 이용되는지 알 수 있음
        • simulate named parameters

        named parameters : function calls that clearly state the name of each parameter within the function call

        • 전달된 argument에 default 값을 복제함, argument로부터 destructure된 object / array는 복제되지 않음
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      // bad
      function createMenu(title, body, buttonText, cancellable) {
      // ...
      }

      createMenu("Foo", "Bar", "Baz", true);

      // good
      function createMenu({ title, body, buttonText, cancellable }) {
      // ...
      }

      createMenu({
      title: "Foo",
      body: "Bar",
      buttonText: "Baz",
      cancellable: true
      });
  2. 하나의 함수는 하나의 행동만

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// bad
function emailClients(clients) {
clients.forEach(client => {
// 1-1. check the client : look up the client
const clientRecord = database.lookup(client);

// 1-2. check the client : check the client status
if (clientRecord.isActive()) {

// 2. email the client
email(client);
}
});
}


// good

// 2.
function emailClients(clients) {
clients
.filter(isClientActive)
.forEach(email);
}

// 1.
function isClientActive(client) {
// 1-1.
const clientRecord = database.lookup(client);

// 1-2.
return clientRecord.isActive();
}
  1. 함수명은 명시적으로 action을 정의하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// bad
function AddToDate(date, month) {
// ...
}

const date = new Date();

// 뭘 추가하는 건지 이름만 보고 알아내기 힘듭니다.
AddToDate(date, 1);


// good
function AddMonthToDate(date, month) {
// ...
}

const date = new Date();
AddMonthToDate(date, 1);
  1. (2)와 비슷한 맥락으로, 재사용 가능하고 테스트가 용이할 수 있도록 하나의 함수는 one level of abstraction을 담당하도록 한다.

❓(2)와 어떤 차이가 있는지?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// bad
function parseBetterJSAlternative(code) {
const REGEXES = [
// ...
];

// 1. tokenize
const statements = code.split(' ');
const tokens = [];
REGEXES.forEach(REGEX => {
statements.forEach(statement => {
// ...
});
});

// 2. lexer (lexical analysis)
const ast = [];
tokens.forEach(token => {
// lex...
});

// 3. parse
ast.forEach(node => {
// parse...
});
}


// good
function tokenize(code) {
const REGEXES = [
// ...
];

const statements = code.split(' ');
const tokens = [];
REGEXES.forEach(REGEX => {
statements.forEach(statement => {
tokens.push( /* ... */ );
});
});

return tokens;
}

function lexer(tokens) {
const ast = [];
tokens.forEach(token => {
ast.push( /* ... */ );
});

return ast;
}

function parseBetterJSAlternative(code) {
const tokens = tokenize(code);
const ast = lexer(tokens);
ast.forEach(node => {
// parse...
});
}
  1. 중복된 코드는 삭제하기

    • 비슷한 일을 하는 함수들이 사소한 차이로 개별적으로 존재하는 경우

      👉 추상화 를 통해 하나의 함수/ 모듈/ 클래스를 사용하여 사소한 차이점을 (argument 등으로) 다루기 : 한 곳만 수정해도 다른 코드에 반영할 수 있음

      e.g. JAVA의 class

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    // bad
    function showDeveloperList(developers) {
    developers.forEach(developers => {
    const expectedSalary = developer.calculateExpectedSalary();
    const experience = developer.getExperience();
    const githubLink = developer.getGithubLink(); // 👈 difference
    const data = {
    expectedSalary,
    experience,
    githubLink
    };

    render(data);
    });
    }

    function showManagerList(managers) {
    managers.forEach(manager => {
    const expectedSalary = manager.calculateExpectedSalary();
    const experience = manager.getExperience();
    const portfolio = manager.getMBAProjects(); // 👈 difference
    const data = {
    expectedSalary,
    experience,
    portfolio
    };

    render(data);
    });
    }


    // good
    function showEmployeeList(employees) {
    employees.forEach((employee) => {
    const expectedSalary = employee.calculateExpectedSalary();
    const experience = employee.getExperience();

    let portfolio = employee.getGithubLink();

    if (employee.type === 'manager') {
    portfolio = employee.getMBAProjects();
    }

    const data = {
    expectedSalary,
    experience,
    portfolio
    };

    render(data);
    });
    }
  2. Object.assign 으로 default object 만들기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// bad
const menuConfig = {
title: null,
body: "Bar",
buttonText: null,
cancellable: true
};

function createMenu(config) {
config.title = config.title || "Foo";
config.body = config.body || "Bar";
config.buttonText = config.buttonText || "Baz";
config.cancellable =
config.cancellable !== undefined ? config.cancellable : true;
}

createMenu(menuConfig);


// good
const menuConfig = {
// minimize null value and set default values to inherit them
title: "Order",
// User did not include 'body' key
buttonText: "Send",
cancellable: true
};

function createMenu(config) {
let finalConfig = Object.assign(
{
title: "Foo",
body: "Bar",
buttonText: "Baz",
cancellable: true
},
config
);
return finalConfig

// follow the order so...
// config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
}

createMenu(menuConfig);
  1. function parameter에 flags 전달하지 않기
    • flags 는 그 자체로 하나 이상의 기능을 하는 것을 의미하므로, 단일 기능을 하는 함수로 나누기!

플래그(flags)

정규 표현식을 생성할 때 플래그를 사용하여 기본 검색 설정을 변경할 수 있습니다.

이렇게 설정된 플래그는 나중에 추가되거나 삭제될 수 없습니다.

플래그(flag) 설명
i 검색 패턴을 비교할 때 대소문자를 구분하지 않도록 설정함.
g 검색 패턴을 비교할 때 일치하는 모든 부분을 선택하도록 설정함.
m 검색 패턴을 비교할 때 여러 줄의 입력 문자열을 그 상태 그대로 여러 줄로 비교하도록 설정함.
y 대상 문자열의 현재 위치부터 비교를 시작하도록 설정함.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// bad
function createFile(name, temp) {
if (temp) {
fs.create(`./temp/${name}`);
} else {
fs.create(name);
}
}


// good
// temp(flags)를 기능별로 개별적인 함수로 나눔
function createFile(name) {
fs.create(name);
}

function createTempFile(name) {
createFile(`./temp/${name}`);
}
  1. Side Effect

    함수가 take a value in and return another value / values 외의 action을 할 경우 side effect가 발생함

    e.g. writing to a file, modifying some global variable, etc.

    • side effect를 발생시키는 함수를 정의할 경우, centralize where you are doing this (하나의 함수로 통일할 것!)
      • pitfall (uncatchable error) 을 피하기 위함
      • e.g. sharing state between objects without any elucidation / saving, using mutable data types that can be written to anything 👉 TypeScript 이용하기, not centralizing where your side effects occur
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    // bad
    // Global variable referenced by following function.
    // If we had another function that used this name, now it'd be an array and it could break the logic it originally had.
    let name = "Ryan McDermott";

    function splitIntoFirstAndLastName() {
    name = name.split(" ");
    }

    splitIntoFirstAndLastName();

    console.log(name); // ['Ryan', 'McDermott'];


    // good
    function splitIntoFirstAndLastName(name) {
    return name.split(" ");
    }

    const name = "Ryan McDermott";
    const newName = splitIntoFirstAndLastName(name);

    console.log(name); // 'Ryan McDermott';
    console.log(newName); // ['Ryan', 'McDermott'];
    • Handling changeable (mutable) values / data by cloning
      • input object를 직접적으로 mutate하는 경우는 많지 않으므로, clone - edit - return 하기
      • improve performance efficiency using great libraries
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // bad
    const addItemToCart = (cart, item) => {
    cart.push({ item, date: Date.now() });
    };


    // good
    const addItemToCart = (cart, item) => {
    // new array
    return [...cart, { item, date : Date.now() }];
    }
  2. global function 사용하지 않기

    • 내장된 library와 충돌할 수 있음
      • 똑같은 이름의 함수가 다른 action
      • 다른 이름의 함수가 같은 action
    • error handling, exception 처리 없이는 해당 API를 사용할 때 문제 발생

    👉 inheritance 이용하기!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// bad
Array.prototype.diff = function diff(comparisonArray) {
const hash = new Set(comparisonArray);
return this.filter(elem => !hash.has(elem));
};


// good
// inheritance
class SuperArray extends Array {
diff(comparisonArray) {
const hash = new Set(comparisonArray);
return this.filter(elem => !hash.has(elem));
}
}
  1. imperative 보다 favor(functional) programming 하기

    Imperative programming : writing your program as a series of instructions (statements) that can actively modify memory (variables, arrays)

    • focuses on how : express the logic of your program based on how the computer would execute it

    Functional programming : writing your program in terms of functions and other mathematical structures

    • A function is just a rule that maps input elements to output
    • concentrates on the what : trying to let you specify the logic of your program as close to actual logic as possible
    • more expressive : writing less code
    • safer : more bugs are prevented by the language ahead of time
    • side-effects are controlled
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const programmerOutput = [
{
name: 'Uncle Bobby',
linesOfCode: 500
}, {
name: 'Suzie Q',
linesOfCode: 1500
}, {
name: 'Jimmy Gosling',
linesOfCode: 150
}, {
name: 'Gracie Hopper',
linesOfCode: 1000
}
];


// bad
let totalOutput = 0;

for (let i = 0; i < programmerOutput.length; i++) {
totalOutput += programmerOutput[i].linesOfCode;
}


// good
const totalOutput = programmerOutput
.map(programmer => programmer.linesOfCode)
.reduce((acc, linesOfCode) => acc + linesOfCode, INITIAL_VALUE);
  1. 조건문(Conditionals) Encapsulation

Encapsulation

bundling data and methods that work on that data within one unit

  • hide the internal representation, or state, of an object from the outside
  • e.g., a class in Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// bad
if (fsm.state === 'fetching' && isEmpty(listNode)) {
// ...
}


// good
function shouldShowSpinner(fsm, listNode) {
return fsm.state === 'fetching' && isEmpty(listNode);
}

if (shouldShowSpinner(fsmInstance, listNodeInstance)) {
// ...
}
  1. 부정조건문 피하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// bad
function isDOMNodeNotPresent(node) {
// ...
}

if (!isDOMNodeNotPresent(node)) {
// ...
}


// good
function isDOMNodePresent(node) {
// ...
}

if (isDOMNodePresent(node)) {
// ...
}
  1. 조건문 피하기
  • 조건문 자체가 함수가 하나 이상의 일을 하고 있음을 의미함

👉 각 case에 해당되는 함수 개별적으로 만들기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// bad
class Airplane {
// ...
getCruisingAltitude() {
switch (this.type) {
case '777':
return this.getMaxAltitude() - this.getPassengerCount();
case 'Air Force One':
return this.getMaxAltitude();
case 'Cessna':
return this.getMaxAltitude() - this.getFuelExpenditure();
}
}
}


// good
class Airplane {
// ...
}

class Boeing777 extends Airplane {
// ...
getCruisingAltitude() {
return this.getMaxAltitude() - this.getPassengerCount();
}
}

class AirForceOne extends Airplane {
// ...
getCruisingAltitude() {
return this.getMaxAltitude();
}
}

class Cessna extends Airplane {
// ...
getCruisingAltitude() {
return this.getMaxAltitude() - this.getFuelExpenditure();
}
}
  1. Type-checking 피하기
  • consistent APIs

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // bad
    function travelToTexas(vehicle) {
    if (vehicle instanceof Bicycle) {
    vehicle.pedal(this.currentLocation, new Location('texas'));
    } else if (vehicle instanceof Car) {
    vehicle.drive(this.currentLocation, new Location('texas'));
    }
    }


    // good
    // case 별로 move function을 달리 하는 것이 아니라,
    // `move`로 동일하게 생성
    function travelToTexas(vehicle) {
    vehicle.move(this.currentLocation, new Location('texas'));
    }
  • TypeScript

    • basic primitive를 이용해서 polymorphism 속성을 활용할 수 없을 때
    • provides you with static typing on top of standard JavaScript syntax
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // bad
    function combine(val1, val2) {
    if (typeof val1 === 'number' && typeof val2 === 'number' ||
    typeof val1 === 'string' && typeof val2 === 'string') {
    return val1 + val2;
    }

    throw new Error('Must be of type String or Number');
    }


    // good
    // ※ with Typescript
    function combine(val1, val2) {
    return val1 + val2;
    }
  1. over-optimising 피하기

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    // bad
    // On old browsers, each iteration with "uncached" `list.length` would be costly
    // (need to recomputate every time it runs for loop)
    // because of `list.length` recomputation. In modern browsers, this is optimized.
    for (let i = 0, len = list.length; i < len; i++) {
    // ...
    }


    // good
    for (let i = 0; i < list.length; i++) {
    // ...
    }
  2. Dead Code 지우기

    • If it’s not being called, get rid of it!
      • keep it in your version history if you still need it
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    // bad
    function oldRequestModule(url) {
    // ...
    }

    function newRequestModule(url) {
    // ...
    }

    const req = newRequestModule;
    inventoryTracker('apples', req, 'www.inventory-awesome.io');


    // good
    function newRequestModule(url) {
    // ...
    }

    const req = newRequestModule;
    inventoryTracker('apples', req, 'www.inventory-awesome.io');

Variables

  • 변수 이름

    1. 의미 있는

    2. 발음하기 쉬운

    1
    2
    3
    4
    5
    // bad
    const yyyymmdstr = moment().format('YYYY/MM/DD');

    // good
    const currentDate = moment().format('YYYY/MM/DD');
    1. 동일한 유형에 동일한 어휘
    1
    2
    3
    4
    5
    6
    7
    // bad
    getUserInfo();
    getClientData();
    getCustomerRecord();

    // good
    getUser();
    1. 검색 가능한 이름 지정하기
    1
    2
    3
    4
    5
    6
    // bad
    setTimeout(blastOff, 86400000);

    // good
    const MILLISECONDS_IN_A_DAY = 86400000;
    setTimeout(blastOff, MILLISECONDS_IN_A_DAY);
    1. 의도를 나타내는
    1
    2
    3
    4
    5
    6
    7
    8
    9
    const address = 'One Infinite Loop, Cupertino 95014';
    const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;

    // bad
    saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]);

    // good
    const [, city, zipCode] = address.match(cityZipCodeRegex) || [];
    saveCityZipCode(city, zipCode);
    1. 암시적인 것 X, 명시적인 것
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    const locations = ['서울', '인천', '수원'];

    // bad
    locations.forEach(l => {
    doStuff();
    doSomeOtherStuff();
    // ...
    // ...
    // ...
    // 잠깐, `l`은 또 뭘까요?
    dispatch(l);
    });

    // good
    locations.forEach(location => {
    doStuff();
    doSomeOtherStuff();
    // ...
    // ...
    // ...
    dispatch(location);
    });
    1. 필요없는 것 지우기
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // bad
    const Car = {
    carMake: 'BMW',
    carModel: 'M3',
    carColor: '파란색'
    };

    function paintCar(car) {
    car.carColor = '빨간색';
    }

    // good
    const Car = {
    make: 'BMW',
    model: 'M3',
    color: '파란색'
    };

    function paintCar(car) {
    car.color = '빨간색';
    }
    1. short circuiting보다 default 매개변수 활용하기
      • default 매개변수 : 매개변수가 undefined 일 때 적용됨
      • 그 외 (‘’, “”, false, null, 0, NaN 등의 falsy 값 포함) 은 적용되지 않음
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // bad
    function createMicrobrewery(name) {
    const breweryName = name || 'Hipster Brew Co.';
    // ...
    }

    // good
    function createMicrobrewery(name = 'Hipster Brew Co.') {
    // ...
    }

1차 세미나

Git

  1. 버전 관리 용이
    1. 수정한 내용 비교 가능
    2. 파일을 이전 상태로 돌릴 수 있음
    3. 프로젝트 자체를 이전 상태로 돌릴 수 있음
    4. 누가, 언제 만들었는지 추적할 수 있음
    5. 파일 복구 가능
  2. 협업 용이
    1. 브랜치로 분기를 지정하여 기능별로 분리하여 작업할 수 있음
      • feature
      • develop
      • release
      • master
    2. glt flow를 이용하여 브랜치 병합 과정에서 충돌을 최대한 피하기 위해서
      • 충돌 시
        1. pull request 을 이용하여 자동으로 merge되는 것을 방지함
        2. 버전 선택 가능
    3. 각자 다른 부분을 작업한 후 합칠 수 있음
  3. 브랜치를 통한 비선형적인 개발
  4. 원격 저장소가 있다면 어디서나 개발 가능 (Github)
    1. 어디서나 clone 받을 수 있음
    2. 하나의 repository를 여러 사람과 공유할 수 있음
    3. remote가 남아있다면 복구 가능
image-20210403152928735
  • LOCAL
    • Working Directory
      • 새로 생성: Untracked
      • 변경됨: Modified
    • Staging Area
      • Commit할 파일들을 모아놓는 공간
    • Repository
      • Commit 후에 버전이 기록되는 공간
      • history 관리
  • REMOTE

Git 관련 용어

  • Working Tree
  • Commit
  • Branch
  • Merge
  • HEAD

Git 기본 명령어

Screenshot 2021-04-03 at 14 47 31

개인 작업 시

  1. local
1
2
3
4
5
git init <folder name>

cd <folder name>

code .
  1. git

    • new Repository 생성

    • 1
      2
      git remote add origin <address>
      git remote -v // 상태 확인
  2. update

1
2
3
git add .
git commit -m "initial commit"
git status
1
git log // log 확인
1
git push origin master // 원격 저장소 master 브랜치 업데이트

WEB

WEB 동작 원리

Screenshot 2021-04-03 at 14 55 24 image-20210403145603056
  • DNS (Domain Name Server)
  • 3-way / 4-way handshake

URL / URI

  • URL
    • http://sopt.org:80/wp
    • 인터넷 상의 자원의 위치
  • URI
    • http://sopt.org:80/wp/url.pdf
    • 인터넷에 있는 자원을 나타내는 식별자

http://sopt.org:80/wp/?page_od=2519

  • protocol
    • http
    • 원거리 통신 장비 사이에서 메시지를 주고받는 규칙
    • http는 www 상에서 하이퍼텍스트를 주고받는 규칙
    • // 없어도 작동함
  • domain name

    • sopt.org
    • 네트워크 상에서 컴퓨터를 식별하는 호스트명
    • DNS에서 IP 주소로 변경해준다
    • e.g. 172.217.25.238 : google.com
  • port

    • 80
    • 네트워크 서비스나 특정 프로세스를 식별하는 논리 단위
    • 다른 방으로 들어가는 문과 같다
    • e.g. 80번: HTTP, 443번: HTTPS
  • path

    • wp
    • 요청한 자원에 대한 웹 서버 내 경로
  • query

    • ?page_id=2519
    • 웹 서버에 제공하는 추가 파라미터
  • IP

    • 통신에 필요한 각 장치를 나타내는 주소
  • HTTP

    • request

      image-20210403150515508
      • http method
    • reponse

      Screenshot 2021-04-03 at 15 24 58
      • status code

HTML

HyperText Markup Language

웹 페이지의 뼈대를 담당한다.

  • HyperText

    • 참조를 통해 한 문서에서 다른 문서로 즉시 접근할 수 있는 텍스트
    • 웹 상에 존재하는 여러 문서끼리 참조할 수 있는 기술
  • Markup Language

    • 태그 등을 이용하여 문서나 데이터의 구조를 명기하는 언어의 한 가지
    • 데이터를 기술하는 정도로만 사용되기에 프로그래밍 언어가 아님
    • e.g. 마크다운
  • <!DOCTYPE html> 명시
  • semantic tag 지원
  • form 기능 개선
  • 다양한 API 지원

Tag

1
<tag attribute="value"> ...content... </tag>
  • 태그 이름은 대소문자 구분이 없다

  • 태그가 엇갈려서 중첩되면 안 된다

  • 여러 속성이 tag에 들어갈 수 있음

  • content

    • 텍스트 / 다른 태그
    • 감싸진 태그의 자식노드가 됨
  • <단독 태그 />

    image-20210403153939010

구성 Tag

<html>

  • 전체 html 을 감싼다
  • <!DOCTYPE html> 을 벗어날 수 없음

<head>

Screenshot 2021-04-03 at 15 41 15
  • <meta>
    • metadata // 기타 정보
  • <style>
    • 외부 style이 아닌 내부에 정의 가능

<body>

Screenshot 2021-04-03 at 15 42 21
  • space / enter 많이 해도 한개 이외에는 반영 안 됨
Screenshot 2021-04-03 at 15 47 30 Screenshot 2021-04-03 at 15 54 09
  • iframe 은 보안 문제가 있으므로 embed 이용하기

블록 / 인라인

  1. 블록
    • 줄 바꿈이 일어나는 형태
    • 영역의 너비가 상위 영역의 전체 너비만큼 늘어남
    • 내부에 다른 요소를 포함할 수 있음
    • <div> 로 블록 요소를 그룹화
  2. 인라인
    • 줄 바꿈이 일어나지 않는 형태
    • 영역의 너비가 하위 영역의 전체 너비만큼 늘어남
    • 내부에 다른 요소를 포함할 수 없음
    • <span> 으로 인라인 요소를 그룹화

Semantic Tag

  • 컴퓨터가 이해하기 쉽도록 구분한 태그
  • 의미를 가지고 있는 블록 요소
Screenshot 2021-04-03 at 15 59 40

기타

  • 주석
  • 특수 문자
Screenshot 2021-04-03 at 16 00 28

CSS

CSS3

  • 웹 문서용
  • 모듈 기반
    • 원하는 모듈만 탑재 가능
    • 필요한 모듈만 빠르게 업데이트 가능
  • 기존의 도구 없이도 화려하고 동적인 스타일 구현 가능
1
<tag style="color: red;"> ...content... </tag>
  1. tag 별로 style 첨부

  2. <head> 안에 style 첨부

  3. 외부 css 파일 import

    1
    <link rel="stylesheet" type="text/css" href="*.css">

적용 우선순위

중요도 (선언 위치)

  1. 태그 내부의 style
  2. <head><style>
  3. 2 내의 @import
  4. <link>로 연결된 css 파일
  5. 4 내의 @import
  6. 브라우저의 기본 css

대상의 명시도

  1. !important
  2. inline 스타일
  3. id 선택자
  4. 클래스 / 가상 선택자
  5. 태그 선택자
  6. 상속된 스타일

코드 순서

늦게 선언된 스타일을 우선 적용

Selector (선택자)

  1. 전체 선택자 *
  2. 태그 선택자
  3. id 선택자 #
  4. class 선택자 .

다중 값 적용 방법

  • 다중 태그는 , 로 구분
  • 다중 속성은 ; 로 구분
  • 다중 속성 값은 , 로 나열

복합 선택자

  • 선택자 사이의 띄어쓰기: 선택자 조합

    h3 p {...}

    • h3 태그 내부의 모든 p 태그
  • 선택자 사이의 > : 자식 선택자

    h3 > p {...}

    • h3 태그 바로 아래의 p 태그

가상 클래스 선택자

Screenshot 2021-04-03 at 16 33 53

Attribute (속성)

Screenshot 2021-04-03 at 16 34 27
  • text-transform
    • UPPERCASE
    • LOWERCASE
Screenshot 2021-04-03 at 16 36 26
  • position

    • absolute
      • parent-context에 맞게
      • context에 관계 없이 사용자가 지정한 위치에 고정되어서
    • relative
      • child-context에 맞게
      • context에 따라 위치 다르게 적용
    • fixed
      • 위치 변하지 않음
  • overflow

    • auto
      • 스크롤 하지 않을 때는 보이지 않음
Screenshot 2021-04-03 at 16 39 17
  • box-sizing
    • border-box 설정
      • border를 포함한 전체 box의 크기가 설정한 값과 일치하게
    • 설정 안 하는 경우
      • 추가 border 등의 값이 반영되어 box size가 달라짐
  • transform, transition 만으로 animation 효과 줄 수 있음

Box Model

Screenshot 2021-04-03 at 16 45 43
  1. content : 요소가 차지하는 공간
  2. padding : 요소와 테두리 사이의 공간
  3. border : 테두리
  4. margin : 다른 요소 사이의 빈 공간

Flexible Box

image-20210403164800193
  1. flex container
    • display
    • flex-direction
    • flex-wrap : 줄 바꿈
    • justify-content : 주 축의 정렬 방법
    • align-items : 교차 축의 정렬 방법
  2. flex items
    • flex-grow : 증가 너비 비율
    • flex-shrink : 감소 너비 비율
    • flex-basis
      • default: 0 1 auto
      • 많이 설정: 1 0 auto

Redux

State Manager

  • Without
    each component has its own storage => spaghetti code
  • With
    has one store without having each storage
  • predictable state container for JavaScript applications
    • unpredictable; random bugs, hard to fix
  • application-wide state
  • reduce function

react component = view

Reducer

  • can have multiple reducers
  • receives a state and do an action
  • reduce function
  • specify how the application’s state changes in response
  • pure function
  • never do something like : mutate arguments, callign an API, call non-pure function

identity reducer

  • getState()
  • dispatch(action)
  • subscribe(listener)

👇but normally uses hooks👇

Hooks

※ for React
react-query.tanstack.com/reference/useQuery
useQuery
Subscribe to our newsletter The latest TanStack news, articles, and resources, sent to your inbox.
react-query.tanstack.com
useReducer
ko.reactjs.org/docs/hooks-reference.html
Hooks API Reference – React
A JavaScript library for building user interfaces
ko.reactjs.org

Making To-Do List

🚀 redux devTools

Do one thing -> make sure it is working -> move on to next one

overview Tree

big loop

  • dispatch: sends the action to the reducer => actions in loop

index.js

👇simplified

  • < TodoItem todo = {todo} onChange={onChangeTodo} >

※ Single component as a single responsibility

  • Presentational Component
    blog.naver.com/backsajang420/221368885149
    [React] Presentational and Container Components
    [React] 프레젠테이션 컴포넌트와 컨테이너 컴포넌트 (Presentational and Container Components)# 시…
    blog.naver.com

프레젠테이션 컴포넌트 (Presentational Component)
프레젠테이션 컴포넌트(Presentational Component) 는 아래와 같은 성질을 갖는다.
● 어떻게 보여지는 지를 책임진다.
컨테이너 컴포넌트 (Container Component)
컨테이너 컴포넌트(Container Component) 는 아래와 같은 성질을 갖는다.
● 어떻게 동작해야 할지를 책임진다.

React with Redux

Authentication

  • Authentication: who you are
  • Authorization: what you are authorized to do

The Authorization Header

HTTP/1.1

  • browser ‘Inspect’ -> Network

Types

Basic

http://www.base64decode.org

Base64 Decode and Encode - Online

www.base64decode.org
Autehntication based on username and password
concatenation with :

  • Don’t store passwords in raw text, always hash it!
  • Don’t use MD5 (Brute Force) since is becoming more insecure with the current computing power
  • USE BCrypt(the standard nowadays): hash same input into different everytime
    npm bcrypt

Token

  • github personal access tokens
    random token is shared between the server and the client, usually on another request
    lasts for short time (normally 30sec)
    Authorization = Bearer

clinet: React, Angular …

JWT (Jason Web Tokens)

https://jwt.io
[algorithm & token type]header-[data: that needs to be secured]payload(userId, iat)-[verifying key]verify signature: no one can change the content
signature => only if I have a secret, generates the signature / if input is different, signature will be different too

  • can’t change the payload if the signature hasn’t been changed
  • most bearer strategy: the token has all the info needed
  • the only thing stored in the server is the stored passphrase
  • the token is composed by the encryption information, the payload encoded in base64 and the signature
  • less control on the token, the only way not to accept it is by using a blacklist

Sesson

  • payload of data that relates to a user
  • persisted in the server and is tagged with the ID
  • writes ID in the cookie (piece of information)-> how we are saved and tracked// and sends it to the browser
  • everytime the browser performs a request to the server, it sends back the cookie with the ID in it

session store: mongodb, file, etc…
npm express-session
npm helmet

  • iframe: build website inside the website (element)

Oauth

  • FireFox
  • user, app and authentication provider
  • lets us authenticate a user through an authentication provider, who manages the account of the user
  • Authenticates a user within the activity of an app
  • The credentials are not leaked to the app
  • BUT gives the provider the information (e.g. google)
    passport.js
    oauth0
    firebase authentication