모듈화: 기본 내보내기와 변수 선언 분리
기본 내보내기는 값만 내보낼 수 있으며 변수 선언과 직접 결합할 수 없습니다.
잘못된 예시
export default const exampleObject = { title: 'ES6' };
올바른 해결책
const exampleObject = { title: 'ES6' };
export default exampleObject;
// 또는 객체 리터럴 직접 내보내기
export default { title: 'ES6' };
모듈 가져오기 패턴
// myModule.js 파일
export default function welcome() { return 'hello'; }
export const release = '2.0';
// 올바른 가져오기
import welcome, { release } from './myModule.js';
// 자주 하는 실수
import { welcome } from './myModule.js'; // undefined 반환
import welcome from 'myModule.js'; // 경로 오류
Set 객체의 고유성 문제
const dataSet = new Set();
dataSet.add({ key: 101 });
dataSet.add({ key: 101 });
console.log(dataSet.size); // 2 (서로 다른 참조)
// 내용 기반 중복 제거
const entries = [{ key: 101 }, { key: 101 }];
const distinctEntries = [...new Map(entries.map(entry =>
[`${entry.key}`, entry])).values()];
Map을 이용한 빈도수 계산
const data = ['x', 'y', 'x', 'z', 'y', 'x'];
const resultMap = new Map();
for (const item of data) {
resultMap.set(item, (resultMap.get(item) ?? 0) + 1);
}
// 결과: {'x' => 3, 'y' => 2, 'z' => 1}
Promise 병렬 처리 패턴
| 메서드 | 동작 | 결과 |
|---|---|---|
Promise.all | 모두 성공 시만 성공 | 결과 배열 |
Promise.race | 첫 번째 처리된 결과 | 단일 값 |
Promise.allSettled | 모든 처리 완료 대기 | 상태 배열 |
const taskA = Promise.resolve(10);
const taskB = Promise.reject('failure');
const taskC = Promise.resolve(30);
const outcomes = await Promise.allSettled([taskA, taskB, taskC]);
/* 출력:
[
{status: 'fulfilled', value: 10},
{status: 'rejected', reason: 'failure'},
{status: 'fulfilled', value: 30}
] */
배열 변환 함수 사용 주의
// 반환값 누락
const multiplied = [1,2,3].map(num => { num * 2 }); // [undefined × 3]
// 해결 방법
const multiplied = [1,2,3].map(num => num * 2);
const multiplied = [1,2,3].map(num => { return num * 2; });
// reduce 초기값 설정
const total = [1,2,3].reduce((sum, current) => sum + current);
const totalWithBase = [1,2,3].reduce((sum, current) => sum + current, 100);
옵셔널 체이닝과 널 병합 연산자
const account = { settings: { username: 'devUser' } };
// 전통적 방법
const username = account && account.settings && account.settings.username;
// 현대적 접근
const username = account?.settings?.username;
const email = account?.contact?.email;
// 안전한 기본값
const displayId = account?.id ?? 'guest123'; // 0이나 ''은 대체되지 않음