tags:

views:

397

answers:

4

HI, I need to write multiple statements inside a conditional operator.

What will be the equivalent of this if condition with conditional operator

var name;
var age;
var passed;

if ( arg == "first" )
{
     name = "John";
     age = "25";
     passed = false;
}
else
{
     name = "Peter";
     age = "29";
     passed = true;
}
+3  A: 

hmhm, do you mean ternary operator?

var passed = arg == "first"
    ? (name = "John", age = "25", false) 
    : (name = "Peter", age = "29", true);

My quick check with embedjs shows that it does more or less work. But why? Why would you need that? It would qualify as a major WTF.

alamar
Actually I need to use these in several cases. So I would like to avoid these if else statements and replace them with conditional operators.
rahul
So, take it, it seems to work.
alamar
While ternary operator works nice in some really simple situations anything beyond that will reduce readability of your code. Not only to your colleagues but to yourself (after few months). If you're after reducing your script's footprint use gzip on your server and don't worry about it.
Rashack
+4  A: 

If you're in a situation where you need to execute statements based on a boolean condition, you should really use if-else. The conditional operator is really meant to return a value from an expression, not to execute full statements. By using the conditional operator, you make your code harder to read and more perilous to debug.

If you insist on using the conditional operator, alamar's solution appears to fit your need quite nicely. However, I recommend you vigorously comment your code. The next time you need to modify your code, that comment could be the difference between taking 60 seconds to understand and taking 0.6 seconds to understand.

And if you do comment it, there's really no bandwidth savings in using the character-wise shorter conditional operator over the if-else statement.

Wesley
+1  A: 

If you need to perform multiple operations as part of a conditional check, consider creating a function for the code you listed and call that function in your code where you need the check. This will keep your code neat and your function understandable.

kimsnarf
+2  A: 

Javascript supports object literals - if all you want is to either instantiate one set of variabels or the other, try something like:

var obj = arg == "first" ? 
            { name : "John", age : "25", passed : false } : 
            { name : "Peter",  age : "29", passed : true };

Afterwards, you could refer to name, age, and passed as obj.name, obj.age, and obj.passed. Depending on how commonly you use these three variables together, you might wish to choose to make them a real class.

Compared to alamar's solution, this does without side effects (beyond the setting of obj, which will likely make your code easier to maintain in the long run.

Eamon Nerbonne