Skip to the content.

New JavaScript Operator (?=) is an Absolute Game Changer

TLDR: The new safe assignment operator (?=) revolutionizes JavaScript error handling, enabling cleaner, more readable code without deep nesting or excessive try-catch blocks.


Image

A remarkable new JavaScript operator has emerged, transforming the approach to error handling!

With the safe assignment operator, redundant patterns can be avoided:

Image

This allows for more straightforward coding:

Image

Deep nesting is eliminated, resulting in significantly cleaner and more readable code.

Instead of encountering errors in cumbersome catch blocks:

Image

All operations can now be executed in a single line.

Rather than loudly failing, ?= silently manages errors, allowing for flexible responses.

Image

Responses can vary:

Image

Errors can be reported without disrupting the flow:

Image

Or the process can be halted immediately:

Image

This feature proves to be a powerful tool for creating guard clauses:

Image

One of the most advantageous aspects of this operator is its capability to manage values depending on the presence of exceptions.

Typically, a mutable variable outside the scope would be utilized for error-free access:

Image

This approach can lead to frustration, particularly when striving for immutability and the variable was previously declared as const.

In the past, it required wrapping in a try, removing const, declaring let outside, and reassigning within catch.

With ?=:

Image

Immutability is preserved, leading to more intuitive code, while eliminating all nesting.

How does it work?

The new ?= operator calls the Symbol.result method internally.

When executing this:

Image

The following occurs:

Image

This implies compatibility with ANY object implementing Symbol.result:

Image

Throwing errors remains an option:

Image

A notable feature is that if result has its own Symbol.result method, ?= will drill down recursively:

Image

Direct usage of the object instead of returning from a function is also possible:

Image

Its versatility allows for seamless integration with both standard and awaited functions:

Image

Using

The ?= operator is compatible with the TypeScript **using** keyword for automatic resource cleanup after use.

❌ Before:

Image

✅ After:

Image

How to use it now

While waiting for native integration of ?= in JavaScript, it can be implemented now using this polyfill:

Direct usage isn’t possible—Symbol.result will be required:

Image

Final thoughts

JavaScript error handling has become much more readable and intuitive with the introduction of the safe assignment operator (?=).

Utilize this operator to write cleaner and more predictable code.

Ref: Tari Ibaba - Medium