LoginSignup
26
38

More than 5 years have passed since last update.

JavaScriptの条件演算子(三項演算子)メモ

Last updated at Posted at 2015-11-03

自分用メモ。

参考

制御式

条件式 ? 式1 : 式2という形で書ける。

条件式には論理値または論理値に変換可能な値を記述します。論理式の結果がtrueの場合には式1が、falseの場合には式2が適応されます

やってみる

Node.jsを使って確認します。

index.js
// big
n = 20;
sign = n >= 0 ? 'big' : 'small';
console.log(sign);
index.js
// 改行しても大丈夫。短いときは1行でそうでない場合、改行すると見やすい
n = 20;
sign = n >= 0 
  ? 'big'
  : 'small';
console.log(sign);
index.js
// 式の部分に関数を実行するにように書いても大丈夫
n = 20;
n >= 0 ? console.log('big') : console.log('small');
index.js
// 100
bool = true;
defaultValue = 100;

n = bool
  ? defaultValue || true
  : false;

console.log(n);
index.js
// true.defaultValueがundefinedなのでtrueが設定される。関数で引数が設定されるか分からない場合などに設定しておくと良さそう
bool = true;
var defaultValue;

n = bool
  ? defaultValue || true
  : false;

console.log(n);

型ごとの条件式について

if (x) ? console.log(true) : console.log(false);というようにことを書く場合にxの型によって書く値が入ったときの条件判定が異なる。

[JavaScript] null とか undefined とか 0 とか 空文字('') とか false とかの判定について

  • undefinedはfalse
  • nullもfalse
  • 文字で空の場合にはfalse
  • 空の配列はtrue
  • 数値の場合には0はfalse、-1などはtrue
  • 真偽値のfalseはfalse
  • 空のオブジェクト({})はtrue

null,undefined,空文字列、falseでの利用ぐらいが良さそう。

26
38
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
26
38