DEV Community

Nikhil Agrawal
Nikhil Agrawal

Posted on

Try...Catch V/s Safe Assignment (?=): A Boon or a Curse for Modern Development?

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");
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
}
Enter fullscreen mode Exit fullscreen mode

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?

Top comments (0)