JavaScript - Safe Assignment Operator
JavaScript - Safe Assignment Operator
JavaScriptSafe 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 usingsafe assignment operatorthat 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 lineusername ?= “Guest”;checks if it’s null or undefined and sets it to”Guest”. Finally,alert(username);shows that username is now”Guest”.
GuestAssign 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
Thecalculatefunction takes a number and returns its double. The variable result is set asnull. The lineresult ?= calculate(5);checks if result is “null”, and since it is, it callscalculate(5), which returns10and assigns it to result. Finally,alert(result);shows that result is now10.
10This operator is supported by modern browsers (Chrome 91+, Firefox 89+, Edge 91+, Safari 15+) and Node.js (14.17.0+)