ES6 이전에는 함수 인수에 기본 값을 설정하는 것이 어려웠다.
ex)
function getLocation(city,country,continent){ if(typeof country === 'undefined'){ contry = 'Italy'; } if(typeof continent === 'undefined'){ continent = 'Europe' } console.log(continet,country,city); } getLocation(undefined,undefined,'Milan'); getLocation(undefined,'Paris','France');
ES6에서는 함수 기본 값 인수를 쉽게 설정 할 수 있다.
ex)
//인수 기본값 설정 function calculatePrice(total,tax=0.1,tip=0.05){ //tax나 tip에 값을 할당 하지 않을 시 기본 값(0.1,0.05) 사용 return total + (total * tax) + (total * tip); } //tax는 0.02가 할당되고 tip에는 기본 값인 0.05가 할당된다. calculatePrice(100,0.02);
위에 와 같이 calculatePrice(100,0.02); 시 tax와 tip은 각각 100과 0.02가 할당되고, tip에는 기본 값인 0.05가 할당되게 된다.
만약 인수의 두번째인 tax에 기본 값을 설정하고 싶다면 undefined를 넣어주면 된다.
ex)
//tax에 기본 값 할당되게 하는 방법 calculatePrice(100,undefined,0.11);
디스트럭처링을 사용하면 함수의 인수를 객체로 만들어 주어진 키에 맞춰 값이 입력되어 매개변수의 순서에 대해 걱정 하지 않아도 된다.
ex)
function calculatePrice2({total =0,tax=0.1,tip=0.05,}={}){ return total + (total * tax) + (total * tip); } const bill = calculatePrice2(({tip:0.015,total:100}))
= {}를 추가해야 인수가 기본적으로 객체로 설정되어 인수로 무엇을 전달했는지에 상관없이 기본 속성을 가진 객체로 기본 설정이 된다.