JavaScript Conditional Shortcut. Moreover, if

Is it possible to have more than one other if statement using a conditional shortcut.

var x = this.checked ? y : z; 
+4
source share
6 answers

That's quite possible. In programming, it is called embedding. Consider this example.

 hasMac = false; hasLinux = false; var x = hasMac ? "Mac User" : hasLinux ? "Linux user" : "User OS Unknown"; // x will be "User OS Unknown" hasMac = false; hasLinux = true; var x = hasMac ? "Mac User" : hasLinux ? "Linux user" : "User OS Unknown"; // x will be "Linux user" hasMac = true; hasLinux = true; // or false, won't matter var x = hasMac ? "Mac User" : hasLinux ? "Linux user" : "User OS Unknown"; // x will be "Mac user" 
+1
source

You can abuse the comma operator because it evaluates both of its operands and returns the second:

 var x = this.checked ? y : doSomething(), doSomethingElse(), z; 

However, this makes the code less readable (and supported) than the corresponding if :

 var x; if (this.checked) { x = y; } else { doSomething(); doSomethingElse(); x = z; } 

Therefore, I would recommend using an if in your case.

+5
source

No, the ternary operator returns one of two expressions based on a Boolean expression.

You can nest them if you want, but this is confusing and difficult to read:

var x = a ? b ? c : d : e

+4
source

Not really, but you can have several nested statements:

 var x = this.checked ? y : (some_other_condition) ? z : z2; 
+2
source

do u mean else if ?

if so you can go like

 var x = this.checked ? y : this.elseifcheck ? z : a; 
+1
source

If you mean:

 var x = this.checked ? y : z : a; 

The answer is no. But you can have a production such as:

 var x = this.checked ? y : ( z > 1 ? z : a ); 
+1
source

All Articles