변수 (Variables)

의미 있고 발음하기 쉬운 변수 이름을 사용하자

// 안좋은 예
const yyyymmddstr = moment().format('yyyy/MM/DD');

// 좋은 예
const currentDate = moment().format('yyyy/MM/DD');

동일한 유형의 변수에 동일한 어휘를 사용하자

// 안좋은 예
getUserInfo();
getClientData();
getCustomerRecord();

// 좋은 예
getUser();

검색 가능한 이름을 사용하자

// 안좋은 예
// 대체 86400000 무엇을 의미하는 걸까?
setTimeout(blastOff, 86400000);

// 좋은 예
// 변수는 다른 사람에게 용도를 알려주는 역할도 한다.
const MILLISECONDS_IN_A_DAY = 86400000;
setTimeout(blastOff, MILLISECONDS_IN_A_DAY);

의도를 나타내는 변수를 사용하자

// 안좋은 예
const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]);

// 좋은 예
// 무작정 코드 길이를 줄이기보단, 다른 사람이 편하게 이해할 수 있는 코드를 작성할 것
const address = 'One Infinite Loop, Cupertino 95014';
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
const [, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);

자신만 알아볼 수 있는 작명을 피하자

// 안좋은 예
const locations = ['서울', '인천', '수원'];
locations.forEach(l => {
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  // 잠깐, `l`은 또 뭘까요?
  dispatch(l);
});

// 좋은 예
const locations = ['서울', '인천', '수원'];
locations.forEach(location => {
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  dispatch(location);
});