JavaScript

참고영상 을 보고 공부한 내역입니다.

1강 script async 와 defer의 차이점 및 앞으로 자바스크립트 공부 방향

  1. head에 script 삽입
    img
  • 사용자가 페이지를 로드하기에 너무 오래걸림
  1. body 끝 부분에 script 삽입

img

  • 페이지 로드는 빠르게 진행

  • js가 의존적인 웹사이트라면 정상적인 페이지를 보기위해 오래걸림

  1. head에 asyn 옵션으로 script 삽입

img

  • 병렬적으로 진행 (빠르게 저장됨)

  • 페이지 로딩 전에 js가 불러와질 수 있음

  1. head에 defer 옵션으로 script 삽입

img

asyn vs defer

asyn - 다운로드 속도에 따라서 먼저 excute (병렬)

defer - 다운로드 후 순서 대로 excute

use strict

비상식적인 변수나 함수를 선언 할 수 없게 만듬

1
2
3
4
5
// 1. Use strict
// added in ES5
// use this for Valina JavaScript
'use strict';
console.log("Hellow World")

2강. 데이터타입, data types, let vs var, hoisting

프로그래밍에서 중요한 점
입력 - 연산 - 출력

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// var (don't ever use this)
// var hoisting (move declaration from bottom to top)
// 어디에 선언 했는지 상관없이 항상 선언을 맨위로 끌어올려주는 것
// has no block scope
age = 4;
var age


// 3. Contant (read)
// use const whenever possible.
// only use let if variable needs to change
const daysIndex = 7;
const maxNumber = 5;

// Note!
// Immutable data type: primitive types, frozen objects (i.e. object.freeze())
// Mutable data types: all objects boy default are mutabe in JS
// favor immutable data type always for a few reasons:
// - security
// - thread safety
// - reduce human mistakes


// 4. Variable types
// primitive, single item: number, string, boolean. undefiedn, symbol
// object. box container
// function, first-class function

const count = 17; //integer
const size = 17.1; //decimal number

console.log(`value: ${count}, type: ${typeof count}`);
//value: 17, type: number
console.log(`value: ${size}, type: ${typeof size}`);
//value: 17.1, type: number

// number - speicla numeric value: infinity, -infinity, NaN
const infinity = 1/0;
const negativeInfinity = -1/0;
const nAn = 'not a Number'/2;

console.log(infinity); //Infinity
console.log(negativeInfinity); //-Infinity
console.log(nAn); //NaN

// boolean
// false: 0, null, undefined, NaN, ''
// true: any other value
const canRead = true;
const test = 3<1; //false
console.log(`value: ${canRead}, type: ${typeof canRead}`)
console.log(`value: ${test}, type: ${typeof test}`)

// null
let nothing = null;
console.log(`value: ${nothing}, type: ${typeof nothing}`)

// undefined
let x;
console.log(`value: ${x}, type: ${typeof x}`)

// symbol, create unique identifiers for objects

const symbol1 = Symbol('id');
const symbol2 = Symbol('id');
console.log(symbol1===symbol2); //false

const gSymbol1 = Symbol.for('id');
const gSymbol2 = Symbol.for('id');
console.log(gSymbol1===gSymbol2); //true
console.log(`value: ${symbol1.description}, type: ${typeof symbol1}`)

// object, real-lif object, data structure
const hyunsoo = {name: 'hyunsoo', age: 27};

// 5. Dynamic typing: dynamically typed language
let text ='hello';
console.log(`value: ${text}, type: ${typeof text}`) //hello string
text = 1;
console.log(`value: ${text}, type: ${typeof text}`) //1 number
text = '7'+5;
console.log(`value: ${text}, type: ${typeof text}`) //75 string
text = '8'/'2';
console.log(`value: ${text}, type: ${typeof text}`) //4 number

3강. 코딩의 기본 operator, if, for loop 코드리뷰 팁

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193

// operator

// 1. String concatenation
console.log('my' + ' cat'); //my cat
console.log('1' + 2); //12
console.log(`string literals: 1 + 2 = ${1+2}`); //string literals: 1 + 2 = 3

// 2. Numeric operators
console.log(1 + 1) //add
console.log(1 - 1) //substract
console.log(1 / 1) //divide
console.log(1 * 1) //multiply
console.log(1 % 1) // remainder
console.log(2 ** 3) //exponentiation


// 3. Increment and decrement operators
let counter = 2;
const preIncrement = ++counter; //3
console.log(`preIncrement: ${preIncrement}, counter: ${counter}`) //3 3
// counter = counter + 1
// preIncrement = counter

const postIncrement = counter++ //4
console.log(`postIncrement: ${postIncrement}, counter: ${counter}`) //3 4
// postIncrement = counter
// counter = counter + 1

const predecrement = --counter //4
console.log(`predecrement: ${predecrement}, counter: ${counter}`) //3 3
// counter = counter - 1
// postIncrement = counter

const postdecrement = counter-- //4
console.log(`postdecrement: ${postdecrement}, counter: ${counter}`) //3 2
// postIncrement = counter
// counter = counter - 1

// 4. Assignment operator
let x = 3;
let y = 6;
x += y;
x -= y;
x *= y;
x /= y;

// 5. Comparison operators
console.log(10 < 6); // less than
console.log(10 <= 6); // less than or equal
console.log(10 > 6); // greater than
console.log(10 >= 6); // greater than or equal

// 6. Logical operator ||(or), &&(and), !(not)

const value1 = true;
const value2 = 4<2;

// || (or), finds the first truthy value
console.log(`or: ${value1 || value2 || check()}`);

// && (and), finds the first falsy value
console.log(`and: ${value1 && value2 && check()}`)

// and or 모두 간단히 true false를 알 수 있는 요소를 앞에다 두어야한다
// or - 1개라도 true면 true
// and - 1개라도 false 면 false

// often used to compress long if-statement
// nullableObject && nullableObject.something
if (nullableObject != null){
nullableObject.something;
}

function check(){
for (let i = 0; i<10;i++){
//wasting time
console.log('이모티콘')
}
return true;
}

// ! (not)
console.log(!value1) //false

// 7. Equality
const stringFive = '5';
const numberFive = 5;

// == loose equality, with type conversion
console.log(stringFive == numberFive) //true
console.log(stringFive != numberFive) //false


// === strict equality, with type conversion
console.log(stringFive === numberFive) //false
console.log(stringFive !== numberFive) //true

// object equality by reference
const a1 = {name: 'hyunsoo'};
const a2 = {name: 'hyunsoo'};
const a3 = a1;
console.log(a1 == a2) //false
console.log(a1 === a2) //false
console.log(a1 === a3) //true


// 8. Conditional Operator: if
// if, else if, else
const name = 'hyunsoo';
if(name === 'hyunsoo'){
console.log('Hello hyunsoo')
} else if (name === 'hyun'){
console.log('Hello hyun')
} else {
console.log('unknown')
}

// 9 Ternary operator: ?
// condition ? value: value2;
console.log(name === 'hyunsoo'? 'yes': 'no');

// 10. Switch statement
// use for multiple if checks
// use for enum-like value check
// use for mutiple type checks in TS
const browser = 'IE';
switch (browser) {
case 'IE':
console.log('hello IE');
break;
case 'Chrome':
console.log('hello IE');
break;
case 'Firefox':
console.log('hello IE');
break;
default:
console.log('same all!');
break;
}

// 11. Loops

// while loop, while the condition is truthy,
// body code is excuted
let i = 3;
while (i>0) {
console.log(`while: ${i}`);
i--;
}

// do while loop, body code is excuted first,
// then check the conditions
do{
console.log(`while: ${i}`);
i--;
} while (i>0);


// for loop, for(begin;condition;step)
for(i = 3; i>0; i--){
console.log(`for: ${i}`);
}

for(i = 3; i>0; i = i - 2){
console.log(`inline variable for: ${i}`);
}

// nested loops
for(let i =0; i<10;i++){
for(let j=0; j<10;j++){
console.log(`i: ${i}, j: ${j}`);
}
}


// break, continue
// Q1. iterate from 0 to 10 and print only even numbers (use continue)
for(let i = 0; i<11;i++){
if(i%2 !== 0){
continue;
}
console.log(`q1: ${i}`);
}

// Q2. iterate from 0 to 10 and pring numbers until reaching 8 (use break)
for(let i = 0; i<11;i++){
if(i > 8){
break;
}
console.log(`q1: ${i}`);
}

4강. Arrow Function은 무엇인가? 함수의 선언과 표현

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
// Function
// - fundamental building block in the program
// - subprogram can be used multiple times
// - performs a task or calculates a value

// 1. Function declaration
// funcition name(param1, param2) { body ... return;}
// one function === one thing
// naming: doSomting, command, verb
// e.g. createCardAndPoint -> createCard, createPoint
// function is object in JS

function printHello(){
console.log('Hello');
}

printHello(); //Hello

function log(message){
console.log(message);
}

log('Hello'); //Hello
log(1234); //1234


// 2. Parameters
// premitive parameters: passed by value
// object parameters: passed by reference
function changeName(obj) {
obj.name = 'coder';
}
const hyunsoo = {name: "hyunsoo"};
changeName(hyunsoo);
console.log(hyunsoo); //{name: "coder"}


// 3. Default parameters (added in ES6)
function showMessage(message, from = 'unknown') {
console.log(`${message} by ${from}`);
}
showMessage('Hi!'); // HI! by unknown

// 4. Rest parameters (added in ES6)
function printAll(...args) {

//1
for(let i = 0; i < args.length; i++){
console.log(args[i]);
}

//2
for(const arg of args){
console.log(arg);
}

//3
args.forEach((arg) => console.log(arg));
}

printAll('dream', 'coding', 'hyunsoo');

// 5. Local scope
let globalMessage = 'global' // global Variable
function printMessage() {
let message = 'hello';
console.log(message);
console.log(globalMessage);

function printAnother() {
console.log(message);
let childMessage = 'hello'
}

// console.log(childMessage); //Error
}

// 6. Return a value
function sum(a, b) {
return a+b;
}
const result = sum(1,2); //3
console.log(`sum: ${sum(1,2)}`);

// 7. Early return, early exit
// bad
function upgrageUser(user) {
if(user.point > 10){
// long upgrade logic ...
}
}

// good
function name(params) {
if(user.point <= 10){
return;
}
// long upgrade logic ...
}


// First-class function
// function are treated like any other variable
// can be assigned as a value to variable
// can be passed as a argument to other functions
// can be returned by another function

// 1. Function expression
// a function declaration can be called earlier than it is defiend. (hoisted)
// a function expression is created when the execution reaches it.

const print = function () {
console.log('print')
};
print();
const printAgain = print;
printAgain();
const sumAgain = sum;
console.log(sumAgain(1,3));

// 2. Callback function using function expression
function randomQuiz(answer, printYes, printNO) {
if (answer === 'love you'){
printYes();
} else {
printNO();
}
}

const printYes = function (){
console.log('YES!')
}

const printNo = function (){
console.log('NO!')
}

randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo);


// Arrow Function
// always anonymous
const simplePrint1 = function () {
console.log('simplePrint');
}

const simplePrint = () => console.log('simplePrint');
const add = (a,b) => a+b;
const simpleMutiply = (a,b) => {
// do something more
return a*b;
};

// IIFE: Immediately Invoke Function Expression
(function hello() {
console.log('IIFE');
})();


// Fun quiz Time
// function calculate(command, a, b)
// command: (add, substract, divide, mutiply, reamainder)

const calculate = (command, a ,b) => {
switch (command) {
case 'add':
console.log(a + b);
break;
case 'substract':
console.log(a - b);
break;
case 'divide':
console.log(a / b);
break;
case 'mutiply':
console.log(a * b);
break;
case 'reamainder':
console.log(a % b);
break;
default:
console.log(`command: ${command}, a: ${a}, b: ${b}`);
break;
}
};

calculate('divide', 5, 1); //5

5강. 클래스와 오브젝트의 차이점(class vs 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
'use strict'

// Object-oriented programming
// class: template
// object: instance of a class
// JavaScript classes
// - introduced in ES6
// - syntactical sugar over prototype-based inheritance

// 1. Class declarations
class Person{
// constructor
constructor(name, age){
// fields
this.name = name;
this.age = age;
}

//method
speak(){
console.log(`${this.name}: hello!`)
}
}

const hyunsoo = new Person('hyunsoo', 27);
console.log(hyunsoo.name); //hyunsoo
console.log(hyunsoo.age); //27
hyunsoo.speak(); //hyunsoo: hello!

// 2. Getter and setters
class User{
constructor(firstName, lastName, age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}

get age(){
return this._age;
}

set age(value){
// if(value < 0){
// throw Error('age can not be negative');
// }
this._age = value < 0 ? 0 : value;
}
}

const user1 = new User('Steve', 'Job', -1);
console.log(user1.age);


// 3. Fields (public, private)
// Too soon!
class Experiment{
publicField = 2;
#privateField = 0;
}

const experiment = new Experiment()
console.log(experiment.publicField);
console.log(experiment.privateField); //undefined


// 4. Static propertied and methods
// Too soon!
// object에 상관없이 class를 통해 선언 및 구현
class Article{
static publisher = 'Dream Coding';
constructor(articleNumber){
this.articleNumber = articleNumber;
}
static printPublisher(){
console.log(Article.publisher);
}
}

const article1 = new Article(1);
console.log(article1.publisher); //undefined
console.log(Article.publisher); //Dream Coding
Article.printPublisher(); //Dream Coding


// 5. inheritance
// a way for one class to extend another class.
class Shape{
constructor(width, height, color){
this.width = width;
this.height = height;
this.color = color;
}

draw(){
console.log(`drawing ${this.color} color!`);
}

getArea(){
return this.width * this.height;
}
}


class Rectangle extends Shape{}
class Triangle extends Shape{
draw(){
super.draw();
console.log('삼각형');
}
getArea(){
return this.width * this.height / 2;
}
}

const rectangle = new Rectangle(20,20,'blue');
rectangle.draw();
console.log(rectangle.getArea());
const triangle = new Triangle(20,20,'red');
triangle.draw();
console.log(triangle.getArea());


// Class checking: instanceOf
console.log(rectangle instanceof Rectangle); //true
console.log(triangle instanceof Rectangle); //false
console.log(triangle instanceof Triangle); //true
console.log(triangle instanceof Shape); //true
console.log(triangle instanceof Object); //true

6강. 오브젝트 넌 뭐니?

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
'use strict'
// Objects
// one of JavaScript's data types.
// a collection of related data and/or functionality
// Nearly all objects in JavaScript are instances of Object
// objects = { key : value };
const obj1 = {} // 'object literal' syntax
const obj2 = new Object(); // 'object construcor' syntax

const name = 'Hyunsoo';
const _age = 4;
print(name,_age);

function print(name,age){
console.log(name);
console.log(age);
}

const hyunsoo = {name : 'hyunsoo', age : 4};
print1(hyunsoo)

function print1(person){
console.log(person.name);
console.log(person.age);
}

// With JavaScript magic (dynamically typed language)
// can add properties later
hyunsoo.hasJob = true;
console.log(hyunsoo.hasJob);

// can delete properties later
delete hyunsoo.hasJob;


// 2. Computed properties
// key should be always string
console.log(hyunsoo.name);
console.log(hyunsoo['name']);

hyunsoo['hasJob'] = true;
console.log(hyunsoo.hasJob);

// 3. Property value shorthand
const person1 = {name : 'bob', age: 2};
const person2 = {name : 'steve', age: 3};
const person3 = {name : 'dave', age: 4};
const person4 = makePerson('hyunsoo', 5);
const person5 = new Person('hyunsoo', 5);
console.log(person4);
console.log(person5);

function makePerson(name, age){
return{
name,
age,
};
}

// 4. Constructor Function
function Person(name, age){
//this = {}
this.name = name;
this.age = age;
// return this;
}

// 5. in operator: property existence check (key in obj)
console.log('name' in hyunsoo); //true
console.log('age' in hyunsoo); //true
console.log('random' in hyunsoo); //false

// 6. for ... in vs for...of
// for (key in obj)
console.clear();

for(let key in hyunsoo){
console.log(key);
}

//for (value of iterable)
const array = [1, 2, 4, 5];
for(let value of array){
console.log(value);
}

// Fun cloning
// Object.assign(dest, [obj1, obj2, obj3 ...])
const user = {name: 'hyunsoo', age: '23'};
const user2 = user;
user2.name = 'coder';
console.log(user) //{name: "coder", age: "23"}

//old way
const user3 = {};
for (let key in user){
user3[key] = user[key];
}

const user4 = {};
Object.assign(user4, user);

7강. 배열 제대로 알고 쓰자. 자바스크립트 배열 개념과 APIs 총정리

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict'

// Array

// 1. Declaration

const arr1 = new Array();
const arr2 = [1,2];

// 2. Index position
const fruits = ['apple', 'banana'];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);

// 3. Looping
// print all fruits

// a. for
for(let i = 0; i < fruits.length; i++){
console.log(fruits[i]);
}

// b. for of
for(let fruit of fruits){
console.log(fruit);
}

// c. foreach
fruits.forEach(function(fruit, index, array) {
console.log(fruit,index,array)
});
// use Arrow Function
fruits.forEach((fruit,index) => console.log(fruit, index));


// 4. Addition, deletion, copy
// note!! shift, unshift are slower than pop, push

// push: add an item, to the end
fruits.push('strawberry', 'peach');
console.log(fruits);

// pop: remove an item from the end
fruits.pop();
console.log(fruits);

// unshift: add an item to the beginning
fruits.unshift('lemon');
console.log(fruits);

// shift: remove an item to the beginning
fruits.shift();
console.log(fruits);

// splice: remove an item by index position
fruits.splice(1, 1); //idx 1부터 1개만 삭제
console.log(fruits);

fruits.splice(1, 1, 'strawberry'); //idx 1부터 1개 삭제후 문자열 삽입
console.log(fruits);

// combine two arrays
const fruits2 = ['peach', 'bear'];
const newFruits = fruits.concat(fruits2);
console.log(`newFruits: ${newFruits}`);

// 5. Searching
// find th index
console.clear()
console.log(fruits)
//indexOf
console.log(fruits.indexOf('apple'));
//lasIndexOf
console.log(fruits.lastIndexOf('apple'))
// includes
console.log(fruits.includes('apple'));

8강. 유용한 10가지 배열 함수들. Array APIs 총정리

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Q1. make a string out of an array
{
const fruits = ['apple', 'banana', 'orange'];
const result = fruits.join(',');
console.log(result);
}

// Q2. make an array out of a string
{
const fruits = '🍎, 🥝, 🍌, 🍒';
const result = fruits.split(',')
console.log(result);
}

// Q3. make this array look like this: [5, 4, 3, 2, 1]
{
const array = [1, 2, 3, 4, 5];
const result = array.reverse();
console.log(result);
}

// Q4. make new array without the first two elements
{
const array = [1, 2, 3, 4, 5];
const result = array.slice(0,2);
console.log(result);
}

class Student {
constructor(name, age, enrolled, score) {
this.name = name;
this.age = age;
this.enrolled = enrolled;
this.score = score;
}
}

const students = [
new Student('A', 29, true, 45),
new Student('B', 28, false, 80),
new Student('C', 30, true, 90),
new Student('D', 40, false, 66),
new Student('E', 18, true, 88),
];

// Q5. find a student with the score 90
{
const result = students.find((student) => student.score === 90);
console.log(result);
}

// Q6. make an array of enrolled students
{
const result = students.filter((student) => student.enrolled);
console.log(result);
}

// Q7. make an array containing only the students' scores
// result should be: [45, 80, 90, 66, 88]
{
const result = students.map((student) => student.score);
console.log(result);
}

// Q8. check if there is a student with the score lower than 50
{
const result = students.some((student)=> student.score < 50);
console.log(result);

const result2 = students.every((student)=> student.score < 50);
console.log(result2);
}

// Q9. compute students' average score
{
const result = students.reduce((prev, curr) => prev + curr.score ,0);
console.log(result/students.length);
}

// Q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88'
{
const result = students.map((student) => student.score).join();
console.log(result)
}

// Bonus! do Q10 sorted in ascending order
// result should be: '45, 66, 80, 88, 90'
{
const result = students.map((student) => student.score).sort().join();
console.log(result)
}

9강. JSON 개념 정리 와 활용방법 및 유용한 사이트 공유 JavaScript JSON

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
'use strict'

// JSON
// JavaScript Object Notation

// 1. Object to JSON
// stringfy(obj)
let json = JSON.stringify(true);
console.log(json)

json = JSON.stringify(['apple', 'banana']);
console.log(json)

const rabbit = {
name: 'tori',
color: 'white',
size: null,
birthDate: new Date(),
jump: () => {
console.log(`${name} can jump`);
},
};

json = JSON.stringify(rabbit);
console.log(json)

// 2. Json to Object
// parse(json)

json = JSON.stringify(rabbit);
const obj = JSON.parse(json);
console.log(obj);

10강. 비동기 처리의 시작 콜백 이해하기, 콜백 지옥 체험 😱 JavaScript Callback

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
'use strict'

// JavaScript is synchronous.
// Execute the code block by orger after hoisting

// Synchronous Callback
function printImmediately(print) {
print();
}

// Asynchronous Callback
function printWithDelay(print,timeout) {
setTimeout(print, timeout)
}

console.log('1'); //동기
setTimeout(() => console.log('2'), 1000); //비동기
console.log('3'); //동기
printImmediately(()=> console.log('hello')); //동기
printWithDelay(() => console.log('async callback'), 2000); //비동기

콜백지옥 예제

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
// Callback Hell example
class UserStorage{
loginUser(id, password, onSuccess, onError){
setTimeout(()=>{
if (
(id === 'hyunsoo' && password === 'dream') ||
(id === 'corder' && password === 'cording')
) {
onSuccess(id);
} else {
onError(new Error('not found'));
}

}, 2000);
}

getRole(user, onSuccess, onError){
setTimeout(() => {
if ( user == 'hyunsoo'){
onSuccess({name: 'hyunsoo', role: 'admin'});
} else {
onError(new Error('no access'));
}
}, 1000);
}
}


const userStorage = new UserStorage();
const id = prompt('enter user id');
const password = prompt('enter user password');

userStorage.loginUser(
id,
password,
user => {
userStorage.getRole(
user,
userWithRole => {
alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role}`);
},
error => {
console.log(error);
}
);
},
error => {
console.log(error);
}
)

11강. 프로미스 개념부터 활용까지 JavaScript Promise

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict'

// Promise is JavaScript Object for asynchronous operation.
// State: pending -> fulfilled or rejected
// Producer vs Consumer

// 1. Producer
// when new Promise is created, the executor runs automatically.
const promise = new Promise((resolve, reject) => {
// doing some heavy work (network, read file)
console.log('doing something...');
setTimeout(()=> {
resolve('hyunsoo');
// reject(new Error('no network'));
},2000);

});


// 2. Consumers: then, catch, finally
promise //
.then((value)=>{
console.log(value);
})
.catch((error)=>{
console.log(error);
})
.finally(()=>{
console.log('finally')
});


// 3. Promise chaning
const fetchNumber = new Promise((resolve,reject)=>{
setTimeout(() => resolve(1), 1000);
})

fetchNumber //
.then(num => num *2)
.then(num => num *3)
.then(num=>{
return new Promise((resolve, reject)=>{
setTimeout(() => resolve(num -1), 1000);
})
})
.then(num => console.log(num));


// 4. Error Handling
const getHen = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve('닭'), 1000);
});

const getEgg = hen =>
new Promise((resolve, reject) => {
// setTimeout(() => resolve(`${hen} => ${'계란'}`), 1000);
setTimeout(() => reject(new Error(`${hen} => ${'계란'}`)), 1000);
});


const cook = egg =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${egg} => ${'계란후라이'}`), 1000);
});


getHen() //
//.then(getEgg) === .then(hen => getEgg(hen))
.then(hen => getEgg(hen))
.catch(error => {
return '빵';
})
.then(egg => cook(egg))
.then(meal => console.log(meal))
.catch(console.log)

10강 콜백지옥 -> promise 적용

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
class UserStorage{
loginUser(id, password){
return new Promise((resolve, reject) => {
setTimeout(()=>{
if (
(id === 'hyunsoo' && password === 'dream') ||
(id === 'corder' && password === 'cording')
) {
resolve(id);
} else {
reject(new Error('not found'));
}
}, 2000);
})
}

getRole(user){
return new Promise((resolve, reject) => {
setTimeout(() => {
if ( user == 'hyunsoo'){
resolve({name: 'hyunsoo', role: 'admin'});
} else {
reject(new Error('no access'));
}
}, 1000);
});
}
}


const userStorage = new UserStorage();
const id = prompt('enter user id');
const password = prompt('enter user password');

userStorage.loginUser(id, password) //
.then(user => userStorage.getRole(user))
.then(user => alert(`Hello ${user.name}, you have a ${user.role}`))
.catch(error => console.log(error))

12강. 비동기의 꽃 JavaScript async 와 await 그리고 유용한 Promise APIs

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
62
63
64
65
66
67
68
// async & await
// clear style of using promise :)

// 1. async
async function fetchUser() {
// do network request in 10 secs ...
return 'hyunsoo';
}

const user = fetchUser();
user.then(user => console.log(user))
console.log(user);


// 2. await
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}

async function getApple() {
await delay(1000);
return 'apple';
}

async function getBanana() {
await delay(1000);
return 'Banana';
}

// function pickFruits() {
// return getApple()
// .then(apple => {
// return getBanana()
// .then(banana =>`${apple} + ${banana}`);
// });
// }

async function pickFruits() {
const applePromise = getApple();
const bananaPromise = getBanana();
const apple = await applePromise;
const banana = await bananaPromise;
return `${apple} + ${banana}`;
}

pickFruits()
.then(ans=>console.log(ans))

// 3. useful Promise APIs

// all
function pickAllFruits() {
return Promise.all([getApple(), getBanana()])
.then(fruits => fruits.join(' + ')
);
}

pickAllFruits() //
.then(fruits => console.log(fruits));


// race
function pickOnlyOne() {
return Promise.race([getApple(), getBanana()]);
}

pickOnlyOne() //
.then(one => console.log(one))