Recently, I discovered the new Safe Assignment Operator (?.=) introduced in JavaScript, and I’m really fascinated by its simplicity. ?
The Safe Assignment Operator (SAO) is a shorthand alternative to the traditional try...catch block. It lets you catch errors inline without writing explicit error-handling code for each operation. Here’s an example:
const [error, response] ?= await fetch("https://api.example.com/data");
That’s it! It’s that easy. If the fetch request throws an error, it’s automatically stored in the error constant; otherwise, the response holds the result. Pretty cool, right?
But wait… there’s more.
When using SAO, you still have to handle errors further down the line, like this:
async function getData() { const [requestError, response] ?= await fetch("https://api.example.com/data"); if (requestError) { handleRequestError(requestError); return; } const [parseError, json] ?= await response.json(); if (parseError) { handleParseError(parseError); return; } const [validationError, data] ?= validation.parse(json); if (validationError) { handleValidationError(validationError); return; } return data; }
While SAO simplifies error handling, it can lead to more verbose code. Compare that with a traditional try...catch block:
async function getData() { try { const response = await fetch("https://api.example.com/data"); const json = await response.json(); const data = validation.parse(json); return data; } catch (error) { handleError(error); return; } }
In this case, try...catch takes only 9 lines of code, while SAO approximately double of it.
So, what do you think? Is the Safe Assignment Operator a time-saver, or does it add unnecessary complexity?
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3