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.

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