How to use optional chaining operator in JavaScript
Consider below line of code.
let { paid, price } = await getCourseBySlug(params.id[0]);
Here getCourseBySlug may return null so destructuring will fail. Because it tries to destructure properties from null
, leading to an error. To handle this scenario, you can use conditional (optional) chaining and default values.
Here’s an example of how you can safely destructure the properties paid
and price
from the result of getCourseBySlug
while handling the case where it returns null
:
Using Optional Chaining and Default Values
let course = await getCourseBySlug(params.id[0]);
let { paid = false, price = 0 } = course || {};
Explanation
- Fetch the Course: Use
await
to fetch the course. - Optional Chaining: Use
course || {}
to provide a default empty object in casecourse
isnull
. - Destructuring with Default Values: Destructure
paid
andprice
from the course object, providing default values (false
forpaid
and0
forprice
) in case they are undefined.
Full Example
Here’s a full example to illustrate this in context:
async function fetchCourseDetails(slug) {
try {
let course = await getCourseBySlug(slug);
let { paid = false, price = 0 } = course || {};
console.log(`Course Paid: ${paid}, Course Price: ${price}`);
} catch (error) {
console.error('Error fetching course details:', error);
}
}
// Usage
fetchCourseDetails(params.id[0]);
Additional Error Handling
You might also want to handle cases where getCourseBySlug
throws an error:
async function fetchCourseDetails(slug) {
try {
let course = await getCourseBySlug(slug);
if (!course) {
console.log('Course not found');
return;
}
let { paid = false, price = 0 } = course;
console.log(`Course Paid: ${paid}, Course Price: ${price}`);
} catch (error) {
console.error('Error fetching course details:', error);
}
}
// Usage
fetchCourseDetails(params.id[0]);
This way, you ensure that your code handles the null
case gracefully, preventing runtime errors caused by trying to destructure properties from null
.
Published on: Jul 27, 2024, 12:28 PM