概要
- JavaScript の新しい文法
?.と??について調べた結果の忘備録です。 - 随時追加されます。
Optional?.Chaining
-
?.により undefined と判定された後は、後続の.を?.にする必要がない。
後続の?.は不要
const obj = {
aaa: {}
}
obj.aaa.bbb // undefined
obj.aaa.bbb?.ccc.ddd // undefined (no error)
-
obj.aaa.bbb?.ccc.dddで、bbb?.は undefined と判定される。 -
.ccc以降は実行されず、直ちに undefined が返る。 -
.dddは実行されないので、エラーにならない。
obj.aaa // {}
obj.aaa?.bbb // undefined
obj.aaa?.bbb.ccc // Uncaught TypeError:
// Cannot read property 'ccc' of undefined
-
obj.aaa?.bbb.cccで、aaa?.は undefined ではないため、?.bbbが実行される。 -
.bbbの後ろに?.がないので、後続の.cccが実行される。 -
.bbbが undefined なので.cccは エラーになる。
-
?.の前項がnullであっても、戻り値はundefinedになる。
const target = null
target?.toString() // undefiend
Nullish ?? Coalescing
-
??の第二項の式は、第一項がundefinedかnullではない場合には評価されない。
第二項は実行されない。
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.)