LoginSignup
0
0

More than 3 years have passed since last update.

javascriptの基礎(条件分岐の特殊な書き方)

Last updated at Posted at 2020-09-10

はじめに

以下のサイトを使用し、javascriptを学習しています。
現代の JavaScript チュートリアル

以下、備忘録として残します。

3項演算子 ‘?’

3項演算子 ‘?’の使い方

let result = condition ? value1 : value2 //condition は評価され、もしも真であれば、'value1' が返却され、そうでなければ 'value2' になる
let accessAllowed = ( age > 18 ) ? true : false;

やらない方がいい場面

(company == 'Netscape') ?
   alert('Right!') : alert('Wrong.');
// 変数に結果を代入していない。このような方法で疑問符演算子を使うことは推奨されていない。(読みにくいから)

上記の場合はif文を使う記述が分かりやすい

if (company == 'Netscape') {
  alert('Right!');
} else {
  alert('Wrong.');
}

NULL合体演算子 '??'

'??'はリストの中から最初の “定義済み” 変数を選択するための短縮構文

  • x = a ?? b の結果は
    • a が null あるいは undefined でなければ a,それ以外の場合は bとなる。以下の処理と同様。
x = (a !== null && a !== undefined) ? a : b;

'??'と'||'の比較

違い

  • '||' は最初の 真 の値を返す
  • '??' は最初の 定義済み の値を返す
let height = 0;
alert(height || 100); // 100(代入されている値0は、false判定となるので)
alert(height ?? 100); // 0(heightが定義されているので)
0
0
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
0
0