javascript 短絡演算( || )を使用して条件式を簡略化する
- 2020.10.02
- javascript
- javascript

javascriptで、短絡演算( || )を使用して条件式を簡略化するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
短絡演算( || )使い方
短絡演算( || )を使用すると、以下ような条件式を簡略化することが可能です。
1 2 3 4 5 6 7 8 |
let x = ''; let y = 'world'; if(x === ''){ console.log(y); }else{ console.log(x); } |
1行に簡略化することが可能です。
1 2 3 4 5 |
let x = ''; let y = 'world'; let hoge = x || y; // xがなければyを表示 console.log(hoge); // world |
xに値があると、以下のような結果となります。
1 2 3 4 5 |
let x = 'hello'; let y = 'world'; let hoge = x || y; console.log(hoge); // hello |
未定義の場合も、変数「y」が表示されます。
1 2 3 4 5 |
let x; let y = 'world'; let hoge = x || y; console.log(hoge); // world |
nullの場合も、同様です。
1 2 3 4 5 |
let x = null; let y = 'world'; let hoge = x || y; console.log(hoge); // world |
複数個あっても、同様に利用できます。
1 2 3 4 5 6 7 8 9 |
let x, y, z; console.log(x || y || z); // undefined y = 1; console.log(x || y || z); // 1 x = 'mebee'; console.log(x || y || z); // mebee |
-
前の記事
javascript canvasタグに正三角形を作成する 2020.10.02
-
次の記事
vuepressのテーマ「vuepress-theme-vdoing」を利用するまでの手順 2020.10.03
コメントを書く