JavaScript ES6 정리 - default, rest parameter

JavaScript ES6 정리 - default, rest parameter

이번 포스팅에서는 ES6에 포함된 default parameter, rest parameter에 대해 알아보자!

default parameter

default parameter는 전달된 파라미터의 값이 없거나, undefined일 경우 설정되는 값을 말한다.

바로 예제를 보자!

const beforeES6 = (a, b, c) => {
  a = a ? a : 4;
  b = b || 5;
  if (!c) {
    c = 6;
  }
  console.log(a, b, c);
};

beforeES6(1);
beforeES6(0, 1);
beforeES6(1, undefined, 3);

/*
Result
1 5 6
4 1 6
1 5 3
*/

default parameter가 없을 경우는 위와 같이 함수 안에서 예외처리를 할 것이다.

그렇다면 default parameter를 사용하면 위 코드를 변경할 수 있을까?

const afterES6 = (a = 4, b = 5, c = 6) => {
  console.log(a, b, c);
};

afterES6(1);
afterES6(0, 1);
afterES6(1, undefined, 3);

/*
Result
1 5 6
0 1 6
1 5 3
*/

코드가 매우 간결해졌다.

두 번째 Result가 다른 이유는 Arrow Function beforeES6가 a의 예외처리를 삼항 연산자로 하였는데 0을 false로 처리하여 4가 나온 것이다.

default parameter에 대해 좀 더 자세히 알아보자!

default parameter는 undefined 또는 누락된 파라미터에 대해서만 작동한다.

const afterES6 = (a = 4, b = 5, c = 6) => {
  console.log(a, b, c);
};

afterES6(1, null, 3);

/*
Result
1 null 3
*/

null에 대해서는 작동하지 않는다는 점을 기억하자!

const test = (x = 1, y = x + 3) => {
  console.log(x, y);
};

test();

const test2 = (y = x + 3, x = 1) => {
  console.log(x, y);
};

test2();

/*
Result
1 4
ReferenceError: Cannot access 'x' before initialization
*/

parameter에도 초기화가 되는 순서가 있다.

test Function에서는 x를 먼저 초기화한 후, 그 값을 y에 할당하기 때문에 문제가 없다.

하지만 test2 Function에서는 y에 초기화되지 않은 x를 할당하기 때문에 ReferenceError가 발생한다.

마지막으로 default parameter를 사용할 경우와 아닐 경우, parameter들은 어떤 변수에 할당되는지 확인하자!

const notUsingDefaultParams = (a, b, c) => {
  var a;
  var b;
  var c;
};

const usingDefaultParams = (a, b, c) => {
  let a;
  let b;
  let c;
};
  • default parameter를 사용하지 않을 경우: var를 사용한 것과 같은 효과
  • default parameter를 사용할 경우: let를 사용한 것과 같은 효과

rest parameter

rest parameter는 함수에 정해져 있는 parameter의 개수를 초과하게 넘겨줄 경우, 초과한 나머지에 대한 변수이다.

설명을 위해 먼저 arguments에 대해 알아보자!

const a = function (a = 1, b = 2, c = 3) {
  console.log(arguments); // 유사 배열 객체 { 0: 1, 1: 2, 2: 3, length: 3, callee: ~~~}
  console.log(a, b, c);
};

a();
a(4);
a(4, 5);
a(4, undefined, 6);
a(4, 5, 6);
a(4, 5, 6, 7, 8, 9, 10);

/*
Result 생략
*/

위 코드에서 arguments는 유사 배열 객체라고 한다.

유사 배열 객체 (Array-Like Object)

  • 각 Property의 키가 인덱스이고 Length라는 Property가 있는 객체
  • 넘겨준 인자, 전체를 받는 객체
  • 실제로 넘겨준 값에만 종속되는 객체

위 유사 배열 객체의 특성으로 a() 실행하면 아무것도 안 들어있다.

※ Arrow Function으로 호출 시 결과 다름

function foo(a, b) {
  a = 1;
  arguments[0] = 2;
  console.log(a, arguments[0]);
}
foo(10, 20);

function f(x, y) {
  //여러 개의 파라미터를 넘겨줄 때 기존 방식
  var rest = Array.prototype.slice.call(arguments, 2);
  console.log(rest);
}
f(1, 2, true, null, undefined, 10);

/*
Result
2 2
[ true, null, undefined, 10 ]
*/

ES6 이전 JS에서는 여러개의 파라미터를 넘겨받기 위해 위와 같이 코딩하였다.

하지만 ES6에서 등장한 rest parameter를 사용하면 아래와 같이 간단하게 여러 개의 파라미터를 넘겨받을 수 있다.

const f = (x, y, ...rest) => {
  console.log(rest);
};
f(1, 2, true, null, undefined, 10);

/*
Result
[ true, null, undefined, 10 ]
*/

※ 결과가 배열인 것 확인

마지막으로 rest parameter는 의미 그대로 나머지 parameter만 받을 수 있다.

따라서, 아래와 같이 코딩하면 Error가 발생한다.

const f = function (_first, ...rest, _last) {
  console.log(_first, _last)
}

/*
Result
Error
*/

※ 오직 한 번만, 매개변수의 가장 마지막에서만 rest parameter 사용 가능

본 포스팅은 인프런 강의 Javascript ES6+ 제대로 알아보기를 공부하며 정리한 포스팅입니다!