JavaScript - Safe Assignment Operator



JavaScript Safe Assignment Operator (?=) is a suggested new feature for JavaScript that makes it easier to handle errors in code. This operator helps developers deal with errors more simply, without having to use complicated try/catch blocks.

It is denoted by (?=) symbol. It is currently under development and not yet part of the official ECMAScript specification.

Syntax

The syntax for using the Safe Assignment Operator is as follows.

variable ?= value;

Examples

Here are the simple and examples of using safe assignment operator that will help to better understand it:

Using Safe Assignment Operator

This example demonstrates how to use the operator to assign a value only if the variable is currently null or undefined.

// Initial variable set to null
let username = null;

// Using the Safe Assignment Operator
// to assign a default value
username ?= "Guest";

// Alerting the result
alert(username); // This will alert "Guest"

Output

The variable username is set as null. The line username ?= "Guest"; checks if it's null or undefined and sets it to "Guest". Finally, alert(username); shows that username is now "Guest".

Guest

Assign a Calculated Value

This example demonstrates how to use the operator to assign a calculated value only if the variable is currently null or undefined.

// Function to perform a simple calculation
function calculate(value) {
    return value * 2; // Simple calculation: double the input
}

// Initial variable set to null
let result = null;

// Using the Safe Assignment Operator to assign the calculated value
result ?= calculate(5); // Assigns 10 if result is null

// Alerting the result
alert(result); // This will alert "10"

Output

The calculate function takes a number and returns its double. The variable result is set as null. The line result ?= calculate(5); checks if result is "null", and since it is, it calls calculate(5), which returns 10 and assigns it to result. Finally, alert(result); shows that result is now 10.

10
This operator is supported by modern browsers (Chrome 91+, Firefox 89+, Edge 91+, Safari 15+) and Node.js (14.17.0+)
Advertisements