JavaScript에서 Spread 연산자 vs Rest 연산자
Source: Dev.to

스프레드 연산자가 하는 일
스프레드 연산자(...)는 배열이나 객체와 같은 기존 컬렉션의 모든 항목을 추출할 때 사용합니다. 보통 할당문의 오른쪽(variable = ...something)에 놓이거나 함수 호출(fn(...something))에서 각 항목을 개별적으로 전달할 때 사용됩니다.
레스트 연산자가 하는 일
레스트 연산자(...)는 개별 항목들을 모아 하나의 컨테이너(보통 배열)로 감쌉니다. 함수 선언(function fn(...params) {})에서 자주 보이며, 함수에 전달된 모든 인자를 하나의 매개변수로 모아줍니다.
스프레드와 레스트의 차이점
| Feature | Spread Operator | Rest Operator |
|---|---|---|
| Purpose | 컨테이너에서 항목을 꺼내는 것 | 항목을 컨테이너에 넣는 것 |
| Syntax | 컬렉션([1, ...nums, 2]) 및 함수 호출(Math.max(...nums))에 사용 | 함수 선언(function sum(...nums) {})에만 사용 |
| Result | 주어진 컬렉션에서 개별 항목들 | 모든 항목을 포함하는 하나의 컬렉션 |
배열 및 객체와 함께 스프레드 사용하기
스프레드 연산자를 사용하면 배열을 병합하거나 값을 추가하고, 객체의 얕은 복사본을 만들 수 있습니다.
const postiveNums = [1,2,3,4];
const negativeNums = [-1, -2, -3, -4];
const user = {
name: "anoop",
salary: "50k",
};
// Merging with 0
console.log([...negativeNums, 0, ...postiveNums]);
// [-1, -2, -3, -4, 0, 1, 2, 3, 4]
// Copy by value
const copy = {...user};
copy.salary("80k");
console.log(user); // salary: "50k"
console.log(copy); // salary: "80k"
실용적인 사용 사례
얕은 복사 만들기
스프레드 연산자로 만든 얕은 복사는 원본 객체를 변경하지 않습니다.
const user = {name: "anoop", isActive: true, salary: "50k"};
const temp = {...user};
temp.name = "dipesh";
temp.salary = "25k";
console.log(temp);
// {name: "dipesh", isActive: true, salary: "25k"}
console.log(user);
// {name: "anoop", isActive: true, salary: "50k"}
값 병합하기
객체(또는 배열)를 결합하고 추가 속성을 넣을 수 있습니다.
const defaultSettings = {
theme: "dark",
font: 18,
notification: true
};
const userPreference = {
font: 24,
notification: false
};
const settings = {
...defaultSettings,
...userPreference
};
console.log(settings);
/*
{
theme: "dark",
font: 24,
notification: false
}
*/
함수와 함께 사용하기
레스트 파라미터를 사용해 알 수 없는 개수의 인자를 모으고, 스프레드 연산자를 사용해 배열 항목을 개별적으로 전달합니다.
// Rest Operator
function sumAll(...nums) {
return nums.reduce((acc, cur) => acc + cur, 0);
}
console.log(sumAll(2, 4, 6, 3)); // 15
// Spread Operator
const nums = [2, 4, 6, 3];
const max = Math.max(...nums);
console.log(max); // 6
요약
- Spread: 컨테이너에서 항목을 추출합니다; 새로운 데이터 구조를 만들거나 인자를 전달할 때 사용합니다.
- Rest: 항목을 컨테이너에 모읍니다; 인자를 캡처할 때 사용합니다.