We’ve all been caught out by undefined properties in JavaScript. Below is a ridiculous example to really highlight the point.
This will blow up with the following error: Uncaught TypeError: Cannot read property 'name' of undefined
.
let user = {};
console.log(user.company.name);
Traditionally to handle this we’d check for the existence of company
like so:
let user = {};
if (user.company) {
console.log(user.company.name);
}
The optional chaining operator ?.
is just a bit less faff.
let user = {};
console.log(user.company?.name);
This would log out undefined
, rather than blowing up.
You could even do something like this.
let user = null;
console.log(user?.company?.name);
Just because you can do the above, doesn’t mean you should. So for example if user
should exist, but company
remains optional
it is a good idea to do some checks on user
and handle an undefined user differently.
Developer, tinkerer, occasionally useful