TIL

[TIL]JavaScript ES6 핵심 문법 정리

namerong 2026. 4. 13. 16:02

1. 클래스 (Class)

ES6에서 도입된 객체 생성 문법으로, 기존 생성자 함수보다 더 직관적이고 구조적으로 객체를 설계할 수 있다.

기본 개념

  • 클래스는 객체를 만들기 위한 설계도
  • new 키워드를 통해 인스턴스 생성
  • constructor는 객체 생성 시 1번 실행되는 초기화 함수
  • 메서드는 prototype에 저장되어 모든 인스턴스가 공유

특징

  • 메서드는 인스턴스마다 생성되지 않고 공유됨 → 메모리 효율
  • new 없이 호출 시 에러 발생

코드 흐름

class Student {
  constructor(name, group) {
    this.name = name;
    this.group = group;
  }

  introduce() {
    console.log(`안녕하세요! ${this.group}반 ${this.name}입니다.`);
  }
}

const studentA = new Student('홍길동', 'A');
const studentB = new Student('홍길순', 'B');

console.log(studentA.introduce === studentB.introduce); // true

2. 화살표 함수 (Arrow Function)

ES6에서 도입된 함수 표현 방식으로, 더 간결한 문법과 this 처리 방식이 특징이다.

기본 문법

const fn = () => {};

특징 정리

  • function → => 로 변경
  • return 한 줄이면 {}와 return 생략 가능
  • 매개변수 1개 → () 생략 가능
  • 객체 반환 시 ()로 감싸야 함
const arrowMsg = () => 'hello';
const square = x => x * x;
const sum = (a, b) => a + b;
const createUser = (id, name) => ({ id, name });

this 차이 (중요)

  • 일반 함수: 호출 시 this 결정
  • 화살표 함수: 외부 스코프의 this를 그대로 사용
this.titles.forEach(title => console.log(this.store));

→ 상위 객체의 this 유지

주의

  • 객체 메서드는 화살표 함수 사용 금지
const obj = {
  name: 'kwon',
  sayHi: () => console.log(this.name) // undefined
}

3. 이터러블 (Iterable)

반복 가능한 데이터 구조를 의미하며 for...of 사용 가능하다.

대표 이터러블

  • 배열(Array)
  • 문자열(String)
  • Map, Set

사용 예시

for (const item of array) {}
for (const char of string) {}

유사 배열 vs 이터러블

구분 설명

유사 배열 인덱스 + length 있음
이터러블 for...of 가능
const arrayLike = {
  0: 'a',
  1: 'b',
  length: 2
};

→ for...of 불가능


Array.from()

유사 배열 → 진짜 배열 변환

const realArray = Array.from(arrayLike);

초기 배열 생성도 가능

const arr = Array.from({ length: 5 }, (_, i) => i + 1);

4. Rest 파라미터 & Spread 문법

같은 ...이지만 역할이 완전히 다름


4-1. Rest Parameter (모으기)

  • 함수 매개변수에서 사용
  • 여러 인자를 배열로 받음
  • 반드시 마지막 위치
function fn(first, ...rest) {
  console.log(rest); // 배열
}

4-2. Spread Syntax (펼치기)

  • 배열/객체를 개별 요소로 분해
Math.max(...numbers);

배열 활용

const merged = [...arr1, ...arr2];
const copy = [...arr1]; // 얕은 복사

객체 활용

const obj = { ...obj1, ...obj2 };

복사 개념

타입 복사 방식

원시값 값 복사
배열/객체 참조(주소) 복사

Spread 사용 시 → 얕은 복사


5. 구조 분해 할당 (Destructuring)

배열이나 객체의 값을 쉽게 꺼내 변수에 할당하는 문법


배열 구조 분해

  • 순서 기반
const [a, b] = arr;

특징

  • 일부 건너뛰기 가능
  • rest 사용 가능
  • 기본값 설정 가능
const [first, ...rest] = arr;
const [a, b = 'default'] = arr;

객체 구조 분해

  • 키 이름 기준 (순서 무관)
const { name, age } = obj;

변수명 변경

const { name: userName } = obj;

기본값

const { job = '없음' } = obj;

rest 활용

const { age, ...rest } = obj;

6. 함수 매개변수 구조 분해

객체를 받을 때 구조 분해를 사용하면 가독성이 좋아짐

function printProductInfo({ id, price, spec: { ram }, producer = '삼성' }) {
  console.log(id, price, ram, producer);
}

장점

  • 순서 신경 안 써도 됨
  • 필요한 값만 추출 가능
  • 코드 간결