Multiple operators within a conditional operator
HI, I need to write multiple statements inside a conditional statement.
What will be equivalent to this if the condition with the conditional operator
var name;
var age;
var passed;
if ( arg == "first" )
{
name = "John";
age = "25";
passed = false;
}
else
{
name = "Peter";
age = "29";
passed = true;
}
a source to share
If you are 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 complete statements. By using the conditional operator, you make your code harder to read and more dangerous to debug.
If you insist on using a conditional operator, alamar's solution seems to suit your needs pretty well. However, I recommend that you comment your code vigorously. Next time you need to change your code, this comment could be 60 seconds difference to understand and 0.6 seconds to understand.
And if you comment that, there is really no bandwidth savings when using the conditional statement with shorter conditionals over the if-else statement.
a source to share
Javascript supports object literals - if you only want to create one set of variables or the other try something like:
var obj = arg == "first" ?
{ name : "John", age : "25", passed : false } :
{ name : "Peter", age : "29", passed : true };
Then you can refer to name, age and be passed as obj.name, obj.age and obj.passed. Depending on how you normally use these three variables together, you might want to make them a real class.
Compared to alamar, this does it with no side effects (outside of the obj setting, which is likely to make your code more maintainable in the long run.
a source to share