3
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.

論理演算を使った値の初期化

Last updated at Posted at 2014-12-06

引数をとる関数に引数がない場合 NaNとなる

もしadd1();が実行されたときに、
引数になにもなかったらNaNになる。

var add1 = function(num){
 num += 1;
 return num;
}

// 実行
add1(); // NaNとなる

引数がない場合に値を設定する

下記の例は引数が存在しなかった場合、
論理演算を使って値を初期化することができる。

var add1 = function(num){
 num = num ||  10
 num += 1;
 return num;
}

// 実行
add(); //11

引数に何もなかったら
引数 = undefined (false) となり、
後方が評価され、numに10が代入される。

num = num || 10
// num = undefined || 10
3
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
3
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?