5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascriptで引数が無い場合のデフォルト値を設定する

Last updated at Posted at 2014-12-29

javascriptの論理演算子が値そのものを返す特性を使います。

function hoge(v) {
  v = v || 'default value';
  // ...
}

引数vに値が入っている場合はそのまま。
値が無い場合は'default value'がセットされます。

if文や三項演算子を使うより
スッキリ見やすく書けます。


いくつかコメントをうけての追記です。
||を使った方法はあくまでテクニックなので万能ではないです。
いただいたコメントをまとめると
このテクニックを使う条件はこんな感じ。

  • 決まった型の引数を取り、それを初期化する
  • 複数の引数をとる

function hoge(v, w) {// v: string, w: number
  v = v || '';
  w = w || 0;
  // ...
}

上記の例で引数の方が何でもアリの場合
型が変わってしまうからダメ

hoge(0, false); // v = '', w = 0

引数が1つの場合、argumentsで判定した方が良い

function hoge(v) {
  if (arguments.length < 1) v = '';
  // ...
}
5
3
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?