DEV Community

Cover image for No need of Try-Catch!! Javascript introduced new safe assignment operator✌
Sanskar Singh
Sanskar Singh

Posted on

No need of Try-Catch!! Javascript introduced new safe assignment operator✌

If you are a javascript developer then you definitely know about try-catch block which is used to deal with errors. But now you can use new Safe Assignment operator proposal (?=)
try-catch blocks lead to nested code making it harder to read and maintain.
?= operator reduces nesting and it gives result of function into tuple.
If an error occurs, it returns [error,null]otherwise it returns [null, result].

Example-

async function fetchData() {
     const [error, response] ?= await fetch("https://api.example.com/data");
     if (error) return handleError(error);
     return response;
   }
Enter fullscreen mode Exit fullscreen mode

Better Error Handling

Placing the error first in the [error, data] ?= structure ensures that errors are handled before processing data, reducing the risk of ignoring errors.

const [error, data] ?= await fetch("https://api.example.com");
Enter fullscreen mode Exit fullscreen mode

Inspired from Rust

The pattern of ?= is inspired from Rust which have more structured error handling.

Summary

The Safe Assignment Operator (?=) is a game-changer for JavaScript error handling, promising to reduce the need for clunky try-catch blocks and make your code cleaner and more secure.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

This is from a draft proposal, which hasn't even been accepted for consideration yet - let alone inclusion in the language. It's a very long way from becoming a part of JS - and might not be accepted for inclusion.

Collapse
 
xiaowo profile image
harry li

still have a long way to go

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay