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,002 times
0
-
have a look at the [ternary operator](http://msdn.microsoft.com/en-us/library/ie/be21c7hw(v=vs.94).aspx) – Sam 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.
![](../../users/profiles/245679.webp)
MD Sayem Ahmed
- 26,780
- 23
- 104
- 174
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 }
![](../../users/profiles/1433392.webp)
Maxime Lorant
- 28,973
- 16
- 79
- 93