[JavaScript] Spread Operator / Rest 문법

 

리액트 강의를 보던 중 '...' 형태의 문법을 많이 사용하는 것을 보고 관련 문법을 정리하고자 한다.

 

'...'는 자바스크립트 ES6에서 추가된 문법이다.

스프레드 연산자, 전개 구문, 펼침 연산자라고도 불리며 배열, 함수, 객체를 다룰 때 매우 편리한 기능을 제공한다고 한다.

 

 

Spread 연산자(...)

스프레드 연산자는 배열이나 객체의 전체나 일부를 빠르게 복사할 수 있게 한다.

...연산자는 연결, 복사 등의 용도로 활용도가 높다.

const a = [1, 2, 3];
const b = [...a, 4, 5, 6];

console.log(b);		// [ 1, 2, 3, 4, 5, 6 ]

 

 

배열에서 spread 연산자 사용

두 개의 배열 결합하기 위해 기존에는 concat 메서드를 사용했지만 ...연산자로 대체 가능하다.

 

concat 메서드 사용할 때

const a = ["red", "orange", "yellow"];
const b = ["green", "blue", "purple"];

const arr = a.concat(b);

 

spread 연산자 사용할 때

const a = ["red", "orange", "yellow"];
const b = ["green", "blue", "purple"];

const arr = [...a, ...b];

 

 

배열을 복사하는 경우 기존에는 slice나 map 함수를 이용했지만 spread 연산자로 대체 가능하다.

slice 함수 사용할 때

const a = ["red", "orange", "yellow"];
const b = a.slice();

b.push("green");
console.log(a);	// ["red", "orange", "yellow"]
console.log(b); // ["red", "orange", "yellow", "green"]

 

map 함수 사용할 때

const a = ["red", "orange", "yellow"];
const b = a.map((item) => item);

b.push("green");
console.log(a);	// ["red", "orange", "yellow"]
console.log(b); // ["red", "orange", "yellow", "green"]

 

spread 연산자 사용할 때

const a = ["red", "orange", "yellow"];
const b = [...a];

b.push("green");
console.log(a);	// ["red", "orange", "yellow"]
console.log(b); // ["red", "orange", "yellow", "green"]

 

 

 

객체에서 spread 연산자 사용

객체에서 spread 연산자를 사용하여 객체의 프로퍼티를 복사하거나 업데이트할 수 있다.

 

객체 복사 & 프로퍼티 추가

let arr = {
	name: "guswjd",
    age: 24
};

arr = {...arr, email: "a@gmail.com"};
console.log(arr);  //{name: "guswjd", age: 24, email: "a@gmail.com"}

 

객체 복사 & 업데이트

let arr = {
	name: "guswjd",
    age: 24
};

arr = {...arr, name: "gus", age: 23};
console.log(arr);  //{name: "gus", age: 23}

 

 

 

Rest 문법

< 배열에서 rest 사용 >

const colors = ["red", "orange", "yellow", "green"];
const [one, ...rest] = colors;

console.log(one);	// red
console.log(rest);	// ["orange", "yellow", "green"]

 

const [...rest, last] = colors;

※ 위의 코드처럼 작성은 불가하다.

 

 

 

< 객체에서 rest 사용 >

let arr = {
	name: "guswjd",
    age: 24,
    email: "aa@gmail.com"
};

const { email, ...rest } = arr;
console.log(email);		// aa@gmail.com
console.log(rest);		// {name: "guswjd", age: 24}
console.log(arr);		// {name: "guswjd", age: 24, email: "aa@gmail.com"}

이때 추출한 값의 이름이 꼭 rest일 필요는 없다.

 

 

 

< 함수에서 rest 사용 >

: 함수를 호출할 때 함수의 파라미터를 spread 연산자로 작성한 형태

: rest 파라미터를 사용해 함수의 파라미터로 오는 값들을 모아 하나의 배열을 생성

 

const calc = (a, b, c, d, e) => {
  let sum = 0;
  if(a) sum += a;
  if(b) sum += b;
  if(c) sum += c;
  if(d) sum += d;
  return sum;
}

const result = calc(10, 100, 1000, 10000);

위의 예시 코드와 같이 파라미터로 넣어준 모든 값들의 합을 계산하는 함수를 작성하려고 한다.

하지만 사용할 파라미터와 받아야 할 파라미터의 값이 다를 수 있으며, 함수의 파라미터가 몇 개를 될 지 모르는 경우가 발생할 수 있다.

이 때 함수에서 rest를 사용하여 해결 가능하다.

 

const calc = (...rest) => {
  return rest.reduce((acc, current) => acc + current, 0);
}

const result = calc(10, 100, 1000, 10000, 100000);

 

반응형