레슨 7 / 9·20분
ES6+ 주요 문법
클래스
ES6 클래스는 프로토타입 기반 상속을 깔끔한 문법으로 제공합니다. constructor에서 초기화하고, 메서드를 정의하며, extends로 상속합니다.
javascript
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
speak() {
return this.name + ": " + this.sound;
}
}
class Dog extends Animal {
constructor(name) {
super(name, "멍멍");
}
fetch(item) {
return this.name + "이(가) " + item + "을 가져왔습니다!";
}
}
const dog = new Dog("바둑이");
console.log(dog.speak()); // "바둑이: 멍멍"
console.log(dog.fetch("공")); // "바둑이이(가) 공을 가져왔습니다!"모듈 시스템 (import / export)
ES 모듈을 사용하면 코드를 파일 단위로 나누어 관리할 수 있습니다. export로 내보내고 import로 가져옵니다.
javascript
// math.js — 이름 붙여 내보내기 (named export)
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
// utils.js — 기본 내보내기 (default export)
export default function formatDate(date) {
return date.toLocaleDateString("ko-KR");
}
// app.js — 가져오기
import formatDate from "./utils.js"; // default
import { PI, add } from "./math.js"; // named
import * as math from "./math.js"; // 전체
console.log(add(2, 3)); // 5
console.log(math.PI); // 3.14159Optional Chaining & Nullish Coalescing
?.(옵셔널 체이닝)은 중간 값이 null/undefined이면 에러 없이 undefined를 반환합니다. ??(널 병합)은 null/undefined일 때만 기본값을 사용합니다.
javascript
const user = {
name: "김철수",
address: { city: "서울" },
};
// Optional Chaining
console.log(user.address?.city); // "서울"
console.log(user.address?.zipcode); // undefined (에러 안 남)
console.log(user.phone?.number); // undefined
// Nullish Coalescing
const port = null ?? 3000; // 3000
const host = "" ?? "localhost"; // "" (빈 문자열은 null이 아님)
const count = 0 ?? 10; // 0 (0은 null이 아님)
// || 와의 차이 — ||는 falsy 값 모두 건너뜀
const a = 0 || 10; // 10 (0은 falsy)
const b = 0 ?? 10; // 0 (0은 null/undefined가 아님)Map과 Set
Map은 키-값 쌍의 컬렉션으로 어떤 타입이든 키로 사용 가능합니다. Set은 중복 없는 값의 컬렉션입니다.
javascript
// Map
const scores = new Map();
scores.set("김철수", 95);
scores.set("이영희", 88);
console.log(scores.get("김철수")); // 95
console.log(scores.size); // 2
for (const [name, score] of scores) {
console.log(name + ": " + score);
}
// Set — 중복 제거
const nums = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(nums)];
console.log(unique); // [1, 2, 3]
// Set 연산
const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);
const union = new Set([...setA, ...setB]); // {1,2,3,4}
const inter = [...setA].filter(x => setB.has(x)); // [2,3]💡
Map은 객체와 달리 삽입 순서가 보장되고, size 속성으로 바로 크기를 알 수 있으며, 어떤 타입이든(함수, 객체 등) 키로 사용할 수 있습니다.