Spread & Rest 파라미터 구문 & 구조 분해 할당

JavaScript · 2021. 6. 1. 00:10

Spread (전개 구문)

  • 배열 또는 객체를 풀어서 인자로 전달 혹은 다른 객체나 배열에 할당할 때 사용
function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

Rest 파라미터 (나머지 구문)

  • 배열 또는 객체의 여러 요소 또는 값을 하나로 압축하여 함수의 인자로 받거나 다른 객체나 배열에 할당할 때 사용
  • 파라미터 개수를 모르거나 개수가 가변적일 때 유용
  • 전개 구문과는 반대의 기능
function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");

// a, one
// b, two
// manyMoreArgs, [three, four, five, six]

구조 분해 할당

  • 배열이나 객체를 해체하여 그 값을 다른 변수에 담는 javascript 표현식
({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}


[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]

({ a, b } = { a: 10, b: 20 });
console.log(a); // 10
console.log(b); // 20
// 객체 양변에 있는 소괄호 ()를 빼면 객체 리터럴이 아닌 블록으로 간주되어 실행되지 않는다.
  • 구조를 맞춰주면 그 자리에 자동으로 할당된다고 생각하면 편할 것 같다.
  • 위 두 예시에서의 ...rest는 나머지 구문이다.
  • 값의 형식 또한 구조에 맞게 가변적이다. (객체를 할당하면 객체, 배열을 할당하면 배열)
  • 함수의 매개변수에서도 동일하게 구조 해체 및 할당이 가능

참고:
-코드스테이츠 유어클래스
-https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/rest_parameters
-https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax
-https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
-https://learnjs.vlpt.us/useful/07-spread-and-rest.html

'JavaScript' 카테고리의 다른 글

Positional Parameter vs. Named Parameter  (0) 2023.03.10
DOM (Document Object Model)  (0) 2021.06.02
자료형, 스코프, 클로저  (0) 2021.05.28
객체 기본 조회와 삭제 + for... in/for ...of  (0) 2021.05.27
배열 기본 메소드  (0) 2021.05.25