// 에드센스

express 앱을 개발하며 자스/타스에 대해 하나씩 배워가고 있다.

오늘은 기본값 파라미터를 사용해보았다.


1. 내용

파라미터에 기본값 파라미터를 설정하면 값이 없거나 undefined가 전달될 경우 지정한 기본값으로 사용한다.

 

 

예시)

function multiply(a, b = 1) {
  return a * b;
}

console.log(multiply(5, 2));
// expected output: 10

console.log(multiply(5));
// expected output: 5

 

 

같은 개념으로 함수를 파라미터로 사용할 때도 기본값을 지정할 수 있다.

function callSomething(thing = something()) {
  return thing
}

let numberOfTimesCalled = 0
function something(){
  numberOfTimesCalled += 1
  return numberOfTimesCalled
}

callSomething()  // 1
callSomething()  // 2

 

 

앞의 파라미터를 뒷쪽의 파라미터의 기본값으로 사용할 수 있다.

function greet(name, greeting, message = greeting + ' ' + name) {
  return [name, greeting, message]
}

greet('David', 'Hi')                      // ["David", "Hi", "HiDavid"]
greet('David', 'Hi', 'Happy Birthday!')   // ["David", "Hi", "Happy Birthday!"]

 

 

 

 


2. 실제로 사용한 상황

express앱을 개발하며 user의 컨트롤러-서비스 부분을 개발하고 있었다.

서비스에서 sequelize ORM을 사용하고 있기에 쿼리문을 간단하게 생성하여 DB를 조작한다.

 

로직에서 service를 호출하는 컨트롤러에 따라 다르게 조회할 컬럼을 설정해야 했었다.

이때 기본값 파라미터를 설정해주는 것만으로 아주 간단하게 문제를 해결할 수 있었다.

 

export const findOneUserInfo = async (
  uid: string,
  attributes: string[] = ['name', 'uid', 'email', 'phone', 'createdAt'],
): Promise<any> => {
  try {
    const result = await User.findOne({
      attributes: attributes,
      where: {
        uid: uid,
      },
    });
    return result;
  } catch (err) {
    return err;
  }
};

코드를 보면 인자로 uid와 attributes를 받는다. 원래는 attributes가 없었는데 기본값 파라미터로 추가해주었다.

 

findOneUserInfo(uid)처럼 uid만 사용하여 호출했을때는 조회할 컬럼이 기본값 파라미터의 

['name', 'uid', 'email', 'phone', 'createdAt']로 지정이 되어 쿼리가 수행된다.

 

하지만 이 컬럼들 이외로 알고싶다면 

findOneUserInfo(uid, ['address', 'gender']) 이런식으로 인자를 넣어주면 된다.

이러면 기본값 파라미터 값에 ['address', 'gender']가 추가된 것이 아닌 ['address', 'gender']만 조회된다. 주의.

 

 

 

 

참고:

+ Recent posts