LoginSignup
0
0

More than 3 years have passed since last update.

[JavaScript] Optional?.Chaining と Nullish ?? Coalescing の忘備録

Last updated at Posted at 2020-07-28

概要

  • JavaScript の新しい文法 ?.?? について調べた結果の忘備録です。
  • 随時追加されます。

Optional?.Chaining

  • ?. により undefined と判定された後は、後続の .?. にする必要がない。
後続の?.は不要
const obj = {
    aaa: {}
}

obj.aaa.bbb             // undefined
obj.aaa.bbb?.ccc.ddd    // undefined (no error)
  1. obj.aaa.bbb?.ccc.ddd で、bbb?. は undefined と判定される。
  2. .ccc 以降は実行されず、直ちに undefined が返る。
  3. .ddd は実行されないので、エラーにならない。
obj.aaa             // {}
obj.aaa?.bbb        // undefined
obj.aaa?.bbb.ccc    // Uncaught TypeError: 
                    // Cannot read property 'ccc' of undefined
  1. obj.aaa?.bbb.ccc で、 aaa?. は undefined ではないため、?.bbb が実行される。
  2. .bbb の後ろに ?. がないので、後続の .ccc が実行される。
  3. .bbb が undefined なので .ccc は エラーになる。
  • ?. の前項が null であっても、戻り値は undefined になる。
const target = null

target?.toString()    // undefiend

Nullish ?? Coalescing

  • ?? の第二項の式は、第一項が undefinednull ではない場合には評価されない。
第二項は実行されない。
function func () {
  console.log('Done second operand.')
  return 2
}

1 ?? func()            // 1 (no message)
false ?? func()        // false (no message)
'' ?? func()           // '' (no message)
NaN ?? func()          // NaN (no message)

undefined ?? func()    // 2 (message: Done second operand.)
null ?? func()         // 2 (message: Done second operand.)
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