-3

How can I assign a value to different variable based on a certain condition?

For example, if now the variable a is true, then I want to assign the string "Hello" to the variable b, but not the variable c.

But if now the variable a is not true, then I hope the string "Hello" could be assigned to the variable c, but not the variable b.

Is there a way to assign a value to different variable based on a certain condition in Javascript?

Like this:

var a = true;
var b, c;
((a) ? b : c) = "Hello";
console.log(b); //This should output "Hello"
console.log(c); //This should output `undefined`

3 Answers 3

0

Try an if... else statement.

var a = true;
var b, c;
if (a) {
  b = "Hello";
} else {
  c = "Hello";
}
console.log(b); //This should output "Hello"
console.log(c); //This should output `undefined`

Sign up to request clarification or add additional context in comments.

Comments

0

No, you cannot choose the target of an assignment as an expression1. You should just write

if (a) {
    b = "Hello";
} else {
    c = "Hello";
}

If you don't want to duplicate the "Hello" expression that constructs the variable, put it in a temporary variable. However it is really rare that you need to assign to different variables. Consider calling a function instead which has the result you want based on your condition:

function chooseOrder(x) {
    return a ? [x, undefined] : [undefined, x];
}
;[b, c] = chooseOrder("Hello");

1: well, there's always an exception. We could for example use setter properties, and dynamically choose the object whose property is assigned:

(a
  ? {set value(v) { b = v; }}
  : {set value(v) { c = v; }}
).value = "Hello";

but this really should be considered a trick with a temporary variable.

Comments

0

You cannot choose the target of an assignment using an expression. An if() ... else is needed for what you're trying to do.

var a = true;
var b, c;
if(a)
  b = "Hello";
else
  c = "Hello";
console.log(b);
console.log(c);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.