rahul
rahul

Reputation: 187020

Multiple statements inside a conditional operator

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;
}

Upvotes: 0

Views: 2898

Answers (4)

Eamon Nerbonne
Eamon Nerbonne

Reputation: 48066

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.

Upvotes: 2

Kim
Kim

Reputation: 1452

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.

Upvotes: 1

Wesley
Wesley

Reputation: 10852

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.

Upvotes: 2

alamar
alamar

Reputation: 19313

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.

Upvotes: 3

Related Questions