nullishとoptional chaining
nullish
node13, 14で使ってみる
❯ node Welcome to Node.js v13.12.0. Type ".help" for more information. > const a = null ?? 1 const a = null ?? 1 ^ Uncaught SyntaxError: Unexpected token '?'
❯ node Welcome to Node.js v14.2.0. Type ".help" for more information. > const a = null ?? 1 undefined > a 1
なにがいいのか
- 空文字の時に短絡評価を回避できる
let myText = ''; // An empty string (which is also a falsy value) let notFalsyText = myText || 'Hello world'; console.log(notFalsyText); // Hello world let preservingFalsy = myText ?? 'Hi neighborhood'; console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
注意点
- && や || とつなげて使うことができない
null || undefined ?? "foo"; // raises a SyntaxError true || undefined ?? "foo"; // raises a SyntaxError
optional chaining
何が良いのか
nullやundefinedの心配をせず、methodの呼び出しや値の参照ができる
例
const adventurer = { name: 'Alice', cat: { name: 'Dinah' } }; const dogName = adventurer.dog?.name; console.log(dogName); // expected output: undefined // もし、?を使わないと、 // Error: Cannot read property 'name' of undefined console.log(adventurer.someNonExistentMethod?.()); // expected output: undefined // もし、?を使わないと、 // Error: adventurer.someNonExistentMethod is not a function // メソッドのときの?の位置おかしくね?って思ったけど、こういうもんだった
nullish最近のことだと思ったが、google検索だと、2018年の記事とか見つかる。アンテナすごい