2022. 1. 22. 22:11ㆍ카테고리 없음
1. let, const
let : 블록 단위 변수
const: 블록 단위 상수
2. 템플릿 리터럴
const myname = "Minsoo";
let message = `My name is ${myname}`
3. 반복문 for in, for of
for in : index 순회
for of : element 순회
for in - i를 index랑 연관지어서 기억하자.
let alphabet = ['a','b','c','d'];
for i in alphabet {
console.log(i); // 0 1 2 3
}
for i of alphabet {
console.log(i); // a b c d
}
4. 기본 매개변수
function printMessage(message = "Hello") {
console.log(message);
}
매개변수에 기본값 지정가능.
5. 화살표 함수
const arrowFunc = () => { console.log("hi"); }
const arrowFuncWithReturn = () => "String Return";
const arrowFuncGeneral = (message = "Bye") => {
console.log("this is general form");
consoel.log(message);
return "See you later";
}
- 화살표 함수는 생성자로 사용할 수 없다.
- 함수가 정의된 스코프에 존재하는 this 를 가리킨다.
- 화살표 함수는 생성될 때 this 가 결정되고 화살표 함수가 어떻게 사용되건, 호출되건, this 는 바뀌지 않는다.
- 객체의 메소드로 화살표 함수를 사용하는 것은 적합하지 않다.
6. 객체 정의
let type = "small";
let weight = "100g";
let objectSugar = {type, weight} // {type : "small", weight : "weight"}
7. 객체 복사
Object.assign(target, source) 메소드가 추가되어 복사가 쉬워졌다.
let a = [1,2,3,4]
let b = Object.assign([], a) // b 와 a는 별개의 배열.
8. Computed Property Name
계산된 속성 이름. 동적으로 오브젝트 키값을 결정하는 것으로 생각하면 쉽다.
예전 자바스크립트는 변수를 오브젝트 키값에 사용하지 못했는데 이를 해결해준다.
let color = 'BLACK'
let KEY = ""
if (name === "BLACK") {
KEY = "BLACK"
} else {
KEY = "WHITE"
}
someObj = {
[KEY] : true,
[`DYNAMIC_${KEY}] : true
}
console.log(someObj) // { BLACK: true, DYNAMIC_BLACK: true}
9. 구조분해 할당 (Destructuring Assignment)
배열, 객체를 변수로 분해해서 할당할 수 있다.
let arr = [1,2,3,4]
let [,,,a] = arr
console.log(a) // 4
let x = true
let y = false
[x, y] = [y,x] // x = false , y = true
let rectangle = {width:30, height:40}
let {width, height} = rectangle
console.log(width) // 30
console.log(height)// 40
10. Spread Operator (전개 구문 연산)
//일반 사용법
function numbers(...arg){
console.log(arg)
}
numbers(1,2,3,4,5) // [1,2,3,4,5]
//대입
let number = [1, 2, 3, 4, 5]
let [a, b, ...c] = number
console.log(a) // 1
console.log(b) // 2
console.log(c) // [3, 4, 5]
//객체 복사
let obj1 = { name: 'foo', age: 30 }
let obj2 = { ...obj1 } // 값 복사
//배열 복사
let arr = [1,2,3,4,5]
let arr2 = [...arr] // arr2 값 복사
11. 클래스
class Marin {
constructor(hp, weapon) {
this.hp = hp
this.weapon = weapon
}
print() {
console.log(hp, weapon)
}
static isTerran = true
static printIsTerran(){
console.log(this.isTerran)
}
}
console.log(Marin.isTerran) // true
let marin = new Marin(50, 5)
class JimRaynor extends Marin { //상위클래스의 생성자를 구현해야 함.
constructor(hp, weapon) {
this.hp = hp
this.weapon = weapon
}
}
let jimRaynor = new JimRaynor(100, 15)
https://ko.javascript.info/classes
자세한 내용은 위 링크 참조
12. 모듈
export / import를 통한 모듈 관리
13. Promise
callback을 method chaining 방식으로 대체할 수 있게 해준다.
callback hell에서 벗어나게 해주지만 async/await처럼 asynchronous한 코드를 synchronous하게 작성하게 해주지는 못한다.
let promise = (reservedValue) => {
return new Promise((res, fail) => {
if (num > 4) {
res(reservedValue) //성공이면,
} else {
fail("err") //에러발생
}
})
}
promise(1000)
.then(reservedValue => console.log(reservedValue))
.catch(err => console.log(err))
14. getter , setter
let obj = {
get propName() {
// getter, obj.propName을 실행할 때 실행되는 코드
},
set propName(value) {
// setter, obj.propName = value를 실행할 때 실행되는 코드
}
};
15. ** , 지수 연산자
var a = 2 ** 3 // 8
16. Arrays.inclues() - 원소 있는지 확인해주는 메소드
const array = [1, 2, 3];
console.log(array.includes(3)); // true
17. async / await
asynchronous한 코드를 synchronous하게 짜게 도와준다.
async function은 return 결과값을 promise로 자동으로 랩핑해준다. 명시적으로 해줘도 되나 결과는 같다.
async function A() {}
var b = A() // b는 프로미스 객체
b = A().then(result => { console.log(result) })
async 함수 실행 결과가 프로미스 객체이므로 then으로 체이닝이 가능하다.
await을 사용하면 async function 결과값을 받을 때까지 기다린다.
await하는 프로미스에서 reject를 호출하면 에러가 호출되며 이는 try catch로 처리해줄 수 있다.
await는 최상위 스코프에서 실행할 수 없으므로 async함수로 래핑하여 호출해줘야한다.
let results = await Promise.all([
fetch(url1),
fetch(url2),
...
]);
results에 프로미스 결과값들이 담기고,
어떤 프로미스에서 에러가 발생시 throw error를 하므로 try catch로 처리해줘야한다.
await all 패턴은 모든 프로미스들이 끝날때까지 기다리는 패턴을 구현해준다.
async-await의 원리에 대해 설명해주는 글. 참고.