My "favorite" error while I'm doing something with JavaScript is "Cannot read properties of undefined". Here's an example that produces that error:
const user = { name: 'Krasimir' };
console.log(user.skills[0]);
// Uncaught TypeError: Cannot read properties of undefined (reading '0')
To prevent such situations, we do checks or use helpers. Reading values from deeply nested properties has always been a source of bugs. Today the language has a feature that solves this problem. It is called optional chaining. It provides safe access to nested fields. When something along the chain is undefined
or null
, the whole expression results in undefined
. For example:
const user = { name: 'Krasimir' };
console.log(user?.skills?.[0]); // undefined