반응형
복잡한 인자를 관리할때
1. 객체로 사용하기
function createCar(name, brand, color, type) {
return {
name,
brand,
color,
type
}
}
function createCar({name, brand, color, type}) {
return {
name,
brand,
color,
type
}
}
첫번째 인자는 중요하고 나머지는 옵션이다는걸 명시적으로 보여줌
function createCar(name, { brand, color, type}) {
return {
name,
brand,
color,
type
}
}
2. 명시적으로 함수를 사용하는 다른 개발자에게 에러를 만들어 줘서 인자를 안전하게 관리할 수 있다.
function createCar({name, brand, color, type}) {
if(!name) {
throw new Error('name is a required')
}
if(!brand) {
throw new Error('brand is a required')
}
}
createCar({name: 'CAR', type: 'SUV' });
3. default value / default parameter
function createCar({name = '', brand ='', color = '', type = false} = {}) {
}
createCar({name: 'CAR', type: 'SUV' });
//name이 필수인경우
//default paramter로 할당된 함수가 실행됨
const required(name) => {
throw new Error('require' + name);
}
function createCar({name = required('name'), brand ='', color = '', type = false} = {}) {
}
createCar({ type: 'SUV' });
반응형
'개발 > javascript&jquery' 카테고리의 다른 글
불필요한 return 사용을 줄이자. void vs return (0) | 2025.01.04 |
---|---|
Rest Parameters 나머지 매개변수 (0) | 2025.01.04 |
[css template bootstrap] Html Contact Us, 문의하기 구글 메일 연동 (0) | 2023.01.23 |
함수선언식 함수표현식 차이 (0) | 2022.07.09 |
ES5 특징 - 변수 Scope(스코프), Hoisting(호이스팅) (0) | 2022.07.09 |