본문 바로가기

ECMAScript 6

Rest 파라미터

Rest 파라미터

#1 기본 문법

Rest 파라미터는 Spread 연산자 (...)를 사용하며 파라미터를 정의한 것이다.

Rest 파라미터를 사용하면 인수 리스트를 함수 내부에서 '배열'로 전달받을 수 있다.

function boo(...rest) {
console.log(Array.isArray(rest));
console.log(rest); // [1, 2, 3, 4, 5]
}

boo(1, 2, 3, 4, 5);

인수는 순차적으로 파라미터와 Rest 파라미터에 할당한다.

function boo(param, ...rest) {
console.log(param); // 1
console.log(rest); // [2, 3, 4, 5]
}

boo(1, 2, 3, 4, 5);
function goo(param1, param2, ...rest) {
console.log(param1); // 1
console.log(param2);; // 2
console.log(rest); // [3, 4, 5]
}

goo(1, 2, 3, 4, 5);

Rest 파라미터는 반드시 마지막 파라미터여야 한다.

function f(...rest, param1, param2) {

}

f(1,2, 3, 4, 5);
// SyntaxError : Rest parameter must be last formal parameter


#2 arguments와 rest 파라미터

ES5 에서는 인자의 개수를 사전에 알 수 없는 가변 인자 함수의 경우, arguments 객체를 통해 인수를 확인했었다.

이 arguments 객체는 함수 호출 시 전달된 인수들의 정보를 담고 있는 순회 가능한 유사 배열 객체이며, 함수 내부에서 지역 변수처럼 사용이 가능하다.
// ES5
var boo = function() {
console.log(arguments);
};

boo(1, 2); // { '0' : 1, '1' : 2 }

가변 인자 함수의 경우 파라미터를 통해 인수를 전달받는 것이 불가능하므로 arguments 객체를 활용하여 인수를 전달받는다.

하지만 arguments 객체는 유사 배열 객체이므로 배열 메소드를 사용하려면 Function.prototype.call을 사용해야 하는 번거로움이 있다.

// ES5
function sum() {
/*
가변 인자 함수는 arguments 객체를 통해 인수를 전달받는다.
유사 배열 객체인 arguments 객체를 배열로 변환한다.
*/
var array = Array.prototype.slice.call(arguments);
return array.reduce(function (pre, cur) {
return pre + cur;
});
}

console.log(sum(1, 2, 3, 4, 5)); // 15

ES6 에서는 rest 파라미터를 사용해 가변 인자 함수 내부에 배열로 전달할 수 있게 되었디.

이렇게 하면 유사 배열인 arguments 객체를 배열로 전환하는 등의 번거로움을 피할 수 있다.

// ES6
function sum(...args) {
console.log(arguments);
console.log(Array.isArray(args))
return args.reduce((pre, cur) => pre + cur);
}

console.log(sum(1, 2, 3, 4, 5)); // 15

하지만 ES6의 화살표 함수에는 함수 객체의 arguments 프로퍼티가 없다.

따라서 화살표 함수로 가변 인자 함수를 구현해야 할 때에는 반드시 rest 파라미터를 사용해야 할 것이다.

var normalFunc = function() {};
console.log(normalFunc.hasOwnProperty('arguments')); // true

const arrowFunc = () => {};
console.log(arrowFunc.hasOwnProperty('arguments')); // false


다음 포스팅에선 Spread 연산자 (...)에 대해서 다뤄보도록 하겠습니다.

감사합니다~~


'ECMAScript 6' 카테고리의 다른 글

객체 리터럴 프로퍼티 기능 확장  (0) 2019.08.13
Spread 연산자  (0) 2019.08.12
화살표 함수 (=>)  (0) 2019.08.10
ES6 템플릿 리터럴  (0) 2019.08.09
let, const 그리고 블록 레벨 스코프  (0) 2019.08.08