JavaScriptで日付に0を付けるときはsliceを使用する

JavaScriptで日付に0を付けるときにif(num < 10)のようにして10未満の時に'0'を付けて返す日付用の関数をたまに見かけるが書き方によっては良くない結果を招くことがある。

たとえば下記のようなコードだと10未満の場合0を付けて返し、そうでなければそのまま返す。

var month03 = 3;
var month12 = 12;

function addZero(num){
  if(num < 10){
    num = '0' + num;
  }
  return num;
};

console.log(addZero(month03) + ' ' + typeof(addZero(month03))); // 03 string
console.log(addZero(month12) + ' ' + typeof(addZero(month12))); // 12 number

一見問題なさそうに見えるがこの場合1桁だとstringで返すが2桁だと型をnumberで返してしまう。

この問題を解消する方法は2つある。

1つ目はreturn '' + num;として必ずstringで返す方法。
2つ目はslice(-2)を使用して常に0を付けて右側の2桁を返す方法。

後者のほうがコードが短くて済むのでslice推奨。

var month03 = 3;
var month12 = 12;

function addZero(num){
  return ('0' + num).slice(-2);
};

console.log(addZero(month03) + ' ' + typeof(addZero(month03))); // 03 string
console.log(addZero(month12) + ' ' + typeof(addZero(month12))); // 12 string