Skip to main content
Piotr Majkutewicz
Back to Blog

Exploring the Safe Assignment Operator in JavaScript

Since JavaScript was created in 1997, the language has evolved significantly, gaining new capabilities and tools that simplify the development of feature-rich applications. One of the latest ECMAScript proposals that could be revolutionary is the Safe Assignment Operator (?=). It enables a radical simplification of error handling using tuples, resulting in cleaner and more consistent code.

Traditional Error Handling

When using promise-based APIs or asynchronous functions, developers often rely on try/catch blocks to handle potential exceptions. A common example is fetching data from an endpoint:

javascript
import fetch from 'node-fetch';

const getTodos = async () => {
  try {
    const responseFromEndpoint = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    if (responseFromEndpoint.status === 200) {
      try {
        const data = await responseFromEndpoint.json();
        return data;
      } catch (error) {
        console.error('Error parsing data:', error);
        return null;
      }
    }
  } catch (error) {
    console.error('Error fetching Todos:', error);
    return null;
  }
};

console.log(await getTodos());

What is the Safe Assignment Operator?

This new proposal introduces the ?= operator, which transforms the result of a function call into a tuple:[error, result]. If an error occurs during execution, the operator returns [error, null]; otherwise, it returns [null, result]. This eliminates the need for deeply nested try/catch blocks.

javascript
const [error, response] ?= await fetch('https://jsonplaceholder.typicode.com/todos/1'); 
// If an error occurs: [Error, null]
// If successful: [null, Response]

Usage Example

Below is a simplified example that fetches a list of todos and handles potential errors in a much more concise way:

javascript
import fetch from 'node-fetch';

const getTodos = async () => {
  const [errorFromEndpoint, responseFromEndpoint] ?= await fetch('https://jsonplaceholder.typicode.com/todos/1');

  if (errorFromEndpoint) {
    console.error('Error fetching data:', errorFromEndpoint);
    return null;
  }

  const [jsonError, jsonData] ?= await responseFromEndpoint.json();

  if (jsonError) {
    console.error('Error parsing JSON:', jsonError);
    return null;
  }

  return jsonData;
};

console.log(await getTodos()); 
// Potential output: { userId: 1, id: 1, title: 'delectus aut autem', completed: false }

Why Use ?= ?

  • Simplified error handling: no more deeply nested try/catch blocks.
  • Cleaner code: shorter and more readable constructs.
  • Consistent behavior: always returns a tuple [error, result].

Current Status and Future

Keep in mind that ?= is still in the proposal phase (ECMAScript). This means that its syntax and behavior may change before being officially adopted into the standard. If you want to try it now, you can use experimental transpiler plugins.

If you have suggestions or want to follow the progress of this proposal, visit the TC39 repositories and join the discussion – every opinion can help shape the future of JavaScript.