Safe Assignment (?=) Expression Summary Assigns the first non-null, non-undefined value to a variable. Syntax variable ?= expression Parameters variable The variable, property, or array element to update. expression Any legal expression. Description The safe assignment operator (?=) computes the value of the expression on the right; compares it to the variable, property, or array element on the left; and, finally, assigns the first non-null, non-undefined value back to the variable, property, or array element on the left. Therefore, if the variable, property, or array element on the left is already not null and not undefined, it will simply retain its value. The expression on the right is evaluated prior to assignment. 123int? x = 2, y = null;x ?= 5; // x remains 2y ?= 5; // y is now 5 If both sides of the safe assignment operator evaluate to null, the value for the variable will remain null. If both sides of the safe assignment operator evaluate to undefined, the value for the variable will remain undefined. The safe assignment operator applies to both existent types and nullable types. Examples Using the safe assignment operator to assign a non-null value 123456import System; int? x = null;Console.log(x); // nullx ?= 5;Console.log(x); // 5 Example with existent types 12345import System; int[] arr = [ 1, 2, 3 ];int+ x = arr[Math.random(100)];x ?= 5; // Possible values for x: 1, 2, 3, 5 Share HTML | BBCode | Direct Link