const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined
console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name?.hoge?.koge;
console.log(dogName);
console.log(adventurer.someNonExistentMethod?.());
// > undefined
// > undefined
しかし、Optional chaining を使うことで上記のコードを簡潔に書くことができます。
let id = null;
if (user) {
id = user.id;
}
``````````````````````````
const id = user?.id;