LoginSignup
13
13

More than 5 years have passed since last update.

存在を確認する関数

Last updated at Posted at 2014-09-02

『JavaScriptで学ぶ関数型プログラミング』O'REILLYで紹介されていた、関数で私がとても便利だなと感じ、よく使うものを紹介させて頂きます。

著者の方が自分のくせを修正するために用いている関数として紹介されているものです。

JavaScriptで学ぶ関数型プログラミング
http://www.oreilly.co.jp/books/9784873116600/

existy.js
//関数existyは、何かの存在の有無を明瞭にします
function existy(x) {

  return x != null;
}

existy(null);
//=>false

existy(undefined);
//=>false

existy({}.notHere);
//=>false

非等値演算子!=を使うことによって、null/undefinedとその他を区別しています。

truthy.js
//関数truthyは、与えられた値がtrueとみなされるかどうかを判定している
function truthy(x) {

  return (x !== false) && existy(x);
}

truthy(false);
//=>false

truthy(undefined);
//=>false

truthy(0);
//=>true

truthy('');
//=>true

わたしは、この関数を処理分岐の条件式などでよく用いています。

以上、お役に立てれば幸いです。

13
13
0

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
13
13