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

Sanskar Singh - Aug 25 - - Dev Community

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.

. .
Terabox Video Player