I recently read a javascript code online and want to convert it to C#. When encountered this line of code, I had no idea what it does: X = (!X ? 8 : X). Please explain.
Asked
Active
Viewed 1,481 times
0
-
have a look at the [ternary operator](http://msdn.microsoft.com/en-us/library/ie/be21c7hw(v=vs.94).aspx) – Sam Marsh Aug 15 '13 at 11:48
-
4i'd prefer `if(!x) x=8;` The ternary doesn't save anything in this particular case. – techfoobar Aug 15 '13 at 11:49
2 Answers
7
It checks whether or not X
is false (contains either 0, empty string, null, or undefined). If it is, the line assigns 8 to X
, otherwise X
retains its original value.

MD Sayem Ahmed
- 28,628
- 27
- 111
- 178
2
It sets the X
var to 8 if !X
is true (so if X
is false). Otherwise, X keep the same value.
So, if X is an empty string, the false
boolean or the 0 number (I might forget some values but well you understand), it'll be set to 8, else it'll keep its original values. It's the same as:
if(!X) { X = 8 }

Maxime Lorant
- 34,607
- 19
- 87
- 97