JavaScriptのNull合体演算子の挙動を確かめてみた

September 20, 2022

使ってみる

let res1 = null ?? 'it is null'
console.log("res1:", res1)

let res2 = 0 ?? 'hoge'
console.log("res2:", res2)

let res3 = false ?? 'hoge'
console.log("res3:", res3)

let res4 = undefined ?? 'it is undefined'
console.log("res4:", res4)

console.log('---')

let res10 = null || 'default'
console.log("res10:", res10)

let res20 = 0 || 'default'
console.log("res20:", res20)

let res30 = false || 'default'
console.log("res30:", res30)

let res40 = undefined || 'default'
console.log("res40:", res40)

コンソール

res1: it is null
res2: 0
res3: false
res4: it is undefined
---
res10: default
res20: default
res30: default
res40: default

ドキュメントにあるように ?? は、null / undefined のとき右の値を返すことが分かります。

参考


SHARE

Profile picture

Written by tamesuu