[JavaScript] spread와 rest

wonyu·2022년 7월 10일
0

spread

spread라는 단어의 의미인 ‘펼치다’에서 알 수 있듯이, spread 연산자를 사용하면 배열, 객체 등 iterable한 객체를 펼칠 수 있다. 즉, 0개 이상의 요소 혹은 키-값 쌍으로 확장시킬 수 있다.

사용 예시

  1. 함수 호출

    function sum(a, b, c) {
      return a + b + c;
    }
    
    const numbers = [1, 3, 5];
    sum(...numbers);
  2. 배열 리터럴과 문자열

    const numbers = [1, 2, 3, 4];
    const newArr = [...numbers, '4', 'five', 6];
    console.log(newArr);
    // [1, 2, 3, 4, '4', 'five', 6]
  3. 객체 리터럴(ECMAScript 2018에서 추가됨)

    const obj = {name: 'yj', age: 20};
    let objClone = {...obj, sex: 'female'};
    console.log(objClone);
    // {name: 'yj', age: 20, sex: 'female'}

rest

spread 연산자와 비슷한 역할을 하는 것처럼 보이지만 용도가 다르다. rest 연산자는 배열, 객체를 분해할 때 사용한다.

spread 연산자는 배열이나 객체를 펼쳐서 여러 개로 만든다면, rest 연산자는 여러 엘리먼트를 하나의 엘리먼트로 압축한다.

특징

  • 하나의 ... 만 존재할 수 있다.
    foo(...one, ...wrong, ...wrong) // X
    const [first, ...rest1, ...rest2] = numbers; // X
  • rest 요소는 마지막 요소여야 한다.
    foo(...wrong,arg2, arg3) // X
    foo(arg1, arg2, ...correct) // O
    const {...rest, arg} = numbers; // X
    const {arg, ...rest} = numbers; // O
  • 함수 파라미터에서의 rest 요소는 Array 인스턴스이므로 Array 메서드를 사용할 수 있다.
    function max(...rest) {
      return rest.reduce((acc, current) => (acc < current ? current : acc))
    }

사용 예시

주로 rest 라는 키워드를 사용하지만, 값의 이름이 꼭 rest일 필요는 없다.

  1. 객체

    const person = {
      name: 'yj',
      age: 20,
      sex: 'female'
    };
    
    const {age, ...rest} = person;
    console.log(age);
    console.log(rest);  // {name: 'yj', sex: 'female'}
  2. 배열

    const numbers = [1, 2, 3, 4, 5, 6];
    const [first, ...rest] = numbers;
    console.log(first);
    console.log(rest);  // [2, 3, 4, 5, 6]

0개의 댓글