[Study/JavaScript] Spread / Rest Parameter

SoShy·2024년 1월 24일

JavaScript_Study

목록 보기
29/36
post-thumbnail

1. Spread 연산자


ES2015에서 새롭게 도입되었으며, 배열을 다룰 때 매우 유용하게 활용 가능한 연산자이다.

Spread 연산자(...)는 객체 또는 배열의 각 요소들을 꺼내서 개별 값으로 펼쳐준다.

const numbers = [1, 2, 3];

console.log(numbers);
console.log(...numbers);
.
.
.
>>> (3) [1, 2, 3]
	1 2 3 

spread 연산자를 활용하면, 배열을 간편하게 복사할 수 있다.

const webPublishing = ['HTML', 'CSS'];
const interactiveWeb = [...webPublishing];

interactiveWeb.push('JavaScript');

console.log(webPublishing);
console.log(interactiveWeb);.
.
.
.
>>> (2) ["HTML", "CSS"]
	(3) ["HTML", "CSS", "JavaScript"]

또한, 아래 예시와 같이, 다른 배열을 복사하면서 요소를 하나 추가하는 것도 가능하다.

const webPublishing = ['HTML', 'CSS'];
const interactiveWeb = [...webPublishing, 'JavaScript'];

console.log(webPublishing);
console.log(interactiveWeb);.
.
.
.
>>> (2) ["HTML", "CSS"]
	(3) ["HTML", "CSS", "JavaScript"]

또한, 여러 배열을 합칠 때에도, spread 연산자 활용이 가능하다.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const arr3 = [...arr1, ...arr2];
console.log(arr3);
.
.
.
>>> (6) [1, 2, 3, 4, 5, 6]

함수를 호출할 때 spread 연산자를 활용하여 배열에 있는 값들을 인자(argument)로 사용할 수 있다.

const introduce = (name, birth, job) => {
  console.log('안녕하세요! 반갑습니다.');
  console.log(`저는 ${name}입니다.`);
  console.log(`${birth}년 생이고,`);
  console.log(`직업은 ${job}입니다.`);
  console.log('잘 부탁드립니다 :)');
};

const myArr = ['코드잇', 2017, '프로그래밍 강사'];
introduce(...myArr);

💡 spread 연산자가 사용된 문은 하나의 값으로 평가되는 게 아닌, 여러 개의 값의 목록으로 평가된다. 즉, 표현식인 문이 아니기 때문에, 변수에 할당될 수 없다.



2. Rest Parameter


rest parameter(...)는 spread 연산자와 유사해보이지만, 동작하는 방식에 차이가 있다.

rest parameter는 여러 개의 인자(argument)를 하나의 파라미터(parameter)로 묶는 방식이고,

spread 연산자는 하나로 묶여있는 값을 각각의 개별 값으로 펼치는 방식이다.

const sumAll = (...args) => {
  let sum = 0;
  for (arg of args) {
    sum += arg;
  }
  return sum;
}

console.log(sumAll(1, 2, 3, 4));
profile
프론트엔드 개발자가 되기 위해 노력 중인 새싹🌱 입니다.

0개의 댓글