Optional Chaining has to be one of my favorite features in JavaScript!
It helps you safely access properties, even if they are undefined
or null
, without throwing any errors.
Instead of writing long, messy code to check if each property exists, you can simply use ?.
. It shortens your code and makes it much cleaner.
Here's an example:
const user = { profile: { name: 'Alice' } };
// Without Optional Chaining
const userName = user && user.profile && user.profile.name;
// With Optional Chaining
const userName = user?.profile?.name;
Give it a try in your next project—I’m sure you'll be relieved to get rid of those "Cannot read property" errors!
To stay updated with more content related to web development and AI, feel free to follow me. Let's learn and grow together!
Top comments (0)