-2

I have used null coalescing operator in return statements like below

return Variable??"undefined";

But the below code,

return Variable??Variable="undefined";

I could not understand how it works, since the second parameter to the operator is a assignment statement and i wonder how the return works.

could some one help me understand

stuartd
  • 70,509
  • 14
  • 132
  • 163
Samuel A C
  • 406
  • 3
  • 16
  • The return-value of an assignement is the value being assigned, so `Variable = "undefined"` returnes `"undefined"`. This can then be returned by your method. – MakePeaceGreatAgain Oct 23 '18 at 15:35
  • The second line of code is both assigning a value to `Variable` if it's null, and returning the value of `Variable`. It's the same as: `if (Variable == null) Variable = "undefined"; return Variable;` This is different than the first line, which will return "undefined" if `Variable` is `null`, but will not assign that value to `Variable` (it will remain `null` after the return). – Rufus L Oct 23 '18 at 15:41
  • Possible duplicate of [Why do assignment statements return a value?](https://stackoverflow.com/questions/3807192/why-do-assignment-statements-return-a-value) – gunr2171 Oct 23 '18 at 15:59
  • While I do not recommend it, something like `A = B = 2;` is valid code, and is the same reason why this works. – Ron Beyer Oct 23 '18 at 16:03

2 Answers2

4

From the docs:

The assignment operator (=) stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result

So the return-value of an assignement is the value being assigned. Variable = "undefined" therefor returns "undefined". This can then be returned by your method. The ?? on the other hand is just a shorthand for a simple if-statement.

So the following is fairly similar to your code:

if(Variable != null)
    return Variable
Variable = "undefined";
return Variable;
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
3

In C# the assign operation also returns the value that was assigned. For example

Value=Value=Value=Value="Hello World"

Is valid code. The Assignment get's evaluated first from right to left. In your case assignment>null coalescing operator. You coudl rewrite your code to

string returnValue="";
if(Variable==null)
    returnValue=Variable="undefined";
else
    returnValue=Variable;
return returnValue;
Eike S
  • 300
  • 1
  • 11