spread와 rest

TIL

... 문법은 사용 위치에 따라 spread 또는 rest로 동작한다.

 

spread

spread 연산자는 배열이나 객체를 펼쳐서 개별 요소로 분리한다.

사용 시점

  • 객체나 배열을 복사하거나 합칠 때
  • 함수 호출 시 배열의 요소를 개별 인수로 전달할 때

 

객체 복사 및 확장

const toy = {
  type: "bear",
  price: 15000,
};
const blueToy = {
  ...toy,
  color: "blue",
};

const yellowToy = {
  ...toy,
  color: "yellow",
};

console.log(blueToy); // { type: 'bear', price: 15000, color: 'blue' }
console.log(yellowToy); // { type: 'bear', price: 15000, color: 'yellow' }

 

배열 합치기

const color1 = ["red", "orange", "yellow"];
const color2 = ["blue", "navy", "purple"];
const rainbow = [...color1, 'green', ...color2];

console.log(rainbow); // [ 'red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple' ]

 

함수 인수로 전달

const print = (a, b, c, d, e, f) => {
  console.log(a, b, c, d, e, f);
};

const numbers = [1, 2, 3, 4, 5, 6];
print(...numbers); // 1 2 3 4 5 6

 

rest

rest 연산자는 나머지 요소들을 하나로 묶어서 배열이나 객체로 만든다.

사용 시점

  • 구조 분해 할당에서 나머지 요소를 묶을 때
  • 함수 매개변수에서 가변 인자를 받을 때

 

구조 분해 할당에서 나머지 묶기

const blueToy = {
  type: "bear",
  price: 15000,
  color: "blue",
};

// 구조분해할당을 통해 프로퍼티의 값을 변수들에 할당
const {type, price, color} = blueToy;

console.log(type); // bear
console.log(price); // 15000
console.log(color); //blue
주의할 점
rest는 항상 마지막 위치에 작성해야 한다. 중간이나 앞에 위치하면 오류가 발생한다.
// TypeError
const {...rest, type} = blueToy; // ❌​

 

배열에서 나머지 요소 묶기

const color = ["red", "orange", "yellow", "green"];
const [c1, c2, ...rest] = color;

console.log(c1, c2); // red orange
console.log(rest); // [ 'yellow', 'green' ]

 

함수 매개변수로 가변 인자 받기

const print = (a, b, ...rest) => {
  console.log(a, b, rest);
};

print(1, 2, 3, 4, 5, 6); // 1 2 [ 3, 4, 5, 6 ]

 

spread와 rest 함께 사용

const print = (...rest) => {
  console.log(rest);
};

const numbers = [1, 2, 3, 4, 5, 6];
print(...numbers); // [ 1, 2, 3, 4, 5, 6 ]

'TIL' 카테고리의 다른 글

[TS] 타입 단언  (0) 2025.10.31
웹페이지를 조작하는 DOM  (0) 2025.10.31
구조 분해 할당  (0) 2025.10.31
[TS] 타입 추론 및 타입 정의 연습  (0) 2025.10.31
[TS] 타입 추론  (0) 2025.10.31
'TIL' 카테고리의 다른 글
  • [TS] 타입 단언
  • 웹페이지를 조작하는 DOM
  • 구조 분해 할당
  • [TS] 타입 추론 및 타입 정의 연습
고견
고견
개발 자국 남기기
  • 고견
    개발자국
    고견
  • 전체
    오늘
    어제
    • 분류 전체보기 (157) N
      • Frontend (29)
        • Next.js (16)
        • JavaScript (7)
      • CS (19) N
        • 자료구조 (9)
        • 알고리즘 (5)
        • 운영체제 (4) N
        • 네트워크 (1) N
      • TIL (93)
      • Dev Log (16)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Pages Router
    문자열
    앱 라우터
    ai 감성 일기장
    페이지 라우터
    javascript
    타입 좁히기
    react
    트러블 슈팅
    algorithm
    바닐라 자바스크립트
    함수 타입
    cs50
    클래스
    알고리즘
    typescript
    배열
    useState
    인터페이스
    memory
    generic
    제네릭
    emotion diary
    자료구조
    CS
    Next.js
    Spa
    C
    Trouble Shooting
    App Router
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
고견
spread와 rest
상단으로

티스토리툴바