이터러블
제너레이터
Map
Set
Symbol
Shortand Properties (간결한 속성 표기법)
{ todo: todo} -> { todo } 로 수정
)Computed Property Name
const key = 'name'
const value = 'John'
const person = {
[key]: value
}
console.log(person) // { name: 'John' }
Lookup Table
function getUserType(type) {
if (type === 'ADMIN') {
return '관리자'
} else if (type === 'INSTRUCTOR') {
return '강사'
} else if (type === 'STUDENT') {
return '수강생'
} else {
return '해당 없음'
}
}
function getUserType(type) {
switch (key) {
case 'ADMIN':
return '관리자'
case 'INSTRUCTOR':
return '강사'
case 'STUDENT':
return '수강생'
default:
return '해당 없음'
}
}
function getUserType(type) {
const USER_TYPE = {
ADMIN: '관리자',
INSTRUCTOR: '강사',
STUDENT: '수강생'
}
return USER_TYPE[type] || '해당 없음'
}
Object Destructuring
function Person(name, age, location) {
this.name = name
this.age = age
this.location = location
}
const poco = new Person('poco', 30, 'korea')
위 코드의 가장 큰 문제점은 강제된 매개변수들의 순서다. 이럴때 구조 분해 할당이 필요하다.
function Person({ name, age, location }) {
this.name = name
this.age = age
this.location = location
}
const poco = new Person({
location: 'korea',
name: 'poco',
age: 30
})
아래코드와 같이 필수적으로 넘겨야 하는 것들과 구조 분해 할당으로 넘길 것들을 분리해서 전달할 수도 있다.
function Person2(name, { age, location }) {
this.name = name
this.age = age
this.location = location
}
const pocoOptions = {
age: 30,
location: 'korea'
}
const poco2 = new Person2('poco', pocoOptions)
아래코드 처럼 배열에서 필요한 부분만 구조 분해 하고 싶을 때는 배열 디스트럭처링보다는 객체 디스트럭처링을 이용해서 가지고 오는 것이 더 좋을 수도 있다.
const orders = ['First', 'Second', 'Third', 'Forth', 'Fifth', 'Sixth']
const st = orders[0]
const rd = orders[2]
const [first, , , , , sixth] = orders
console.log(first, sixth) // First Sixth
const { 0: first2, 5: sixth2 } = orders
console.log(first2, sixth2) // First Sixth
Object.freeze
객체를 동결시킬 때 주의해야 할 점은 중첩 객체는 동결되지 않는다는 것이다. 이는 얕은 복사때문이다.
const STATUS = Object.freeze({
PENDING: 'PENDING',
SUCCESS: 'SUCCESS',
FAIL: 'FAIL',
OPTIONS: {
GREEN: 'GREEN',
RED: 'RED'
}
})
// 동결이 잘 되었는지 확인하기
console.log(Object.isFrozen(STATUS)) // true
console.log(Object.isFrozen(STATUS.SUCCESS)) // true
console.log(Object.isFrozen(STATUS.OPTIONS)) // false
STATUS.OPTIONS.GREEN = 'blue'
console.log(STATUS.OPTIONS.GREEN) // blue
깊은 복사를 하기 위해서는 따로 함수를 만들어서 중첩 객체를 순회해서 동결시켜야 한다.
function deepFreeze(targetObj) {
Object.keys(targetObj).forEach((key) => {
const value = targetObj[key]
if (typeof value === 'object' && value !== null) {
deepFreeze(value) // 객체나 배열이면 재귀적으로 동결
}
})
return Object.freeze(targetObj)
}
deepFreeze(STATUS)
console.log(Object.isFrozen(STATUS.OPTIONS)) // true
STATUS.OPTIONS.GREEN = 'green'
console.log(STATUS.OPTIONS.GREEN) // blue
OPTIONS를 확인해보면 true를 출력하고 기존에 blue로 변경되어있던 GREEN에 값을 green으로 수정해보려고 해도 이번에는 동결이 되어 있기 때문에 수정이 불가능해서 그대로 blue를 출력한다.