flix
flix

Reputation: 1974

is it possible to handle 2 variable to changing if/else condition is true on ES6?

Let say I have a code like this

var a, b;
b = 1;
var c = b > 0 ? a = 1 /*and c = 2*/ : a = 0 /*and c = 1*/;
console.log(a + c);

Is there any way to make c = 2 and a = 1 with above code?

Upvotes: 3

Views: 131

Answers (5)

Redu
Redu

Reputation: 26161

DRY coding requires;

var a,
    b = 1;
var c = (b > 0 ? a = 1 : a = 0) + 1;
console.log(a + c);

Upvotes: 0

Kamal Singh
Kamal Singh

Reputation: 1000

One more trick is using below code block

var a,b,c;
b=1;
b > 0 ? ((a=1) && (c = 2)) : ((c = 1) && (a=0));
alert(a + "   " + c);

This is the methodology used by the code minifier in Javascript. Such type of statements should be used with precautions. Let me explain how it works

Case b = 1

the condition b > 0 is true. So the first part is evaluated. It has 2 parts with && separated. It means both statements will get evaluated because first statement evaluates totrue (unless first statenent returns false, this is where precaution is needed). Assigning value to some variable returns the same value. So this test case passes.

Case b = -1

the condition b > 0 fails. Again we have 2 statements concatinated with &&, so both statements again gets evaluates. Here you see that I have placed a = 0 as second statement. This is because when I assign a = 0 it will return assigned value that is 0 and in Javascript true = 1 and false = 0. So placing it as first statement will lead to unevaluated second statement.

Hope you understand the scenario and usage care.

The most pretty forward way without confusion would be using comma operator as mentioned in previous answers

var a,b,c;
b=1;
b > 0 ? (a=1, c = 2) : (a = 0, c = 1);
alert(a + "   " + c);

The && and , technique is used by code minifier altogether.

Upvotes: 0

Bergi
Bergi

Reputation: 664548

I would recommend an old-fashioned

var a, c, b = 1;
if (b > 0) {
  a = 1;
  c = 2;
} else {
  a = 0
  c = 1;
}
console.log(a + c);

If your specific case allows it, you might also do

var a = b > 0 ? 1 : 0;
var c = a + 1;

If you're looking for a way to assign multiple values to multiple variables at once, ES6 destructuring is the solution:

var {a, c} = b > 0 ? {a: 1, c: 2} : {a: 0, c: 1};

Upvotes: 0

Rajesh
Rajesh

Reputation: 24925

As an alternate to @Ori Drori's answer, you can even try something like this:

var b = 1
var a = b > 0 ? 1 : 0;
var c = b + a;

console.log(a, c)

Upvotes: 3

Ori Drori
Ori Drori

Reputation: 191976

You can wrap the expression inside the ternary with brackets, and use the comma operator to return the number you want to assign to c.

var a, b = 1
var c = b > 0 ? (a=1, 2) : (a=0, 1)

console.log(a, c)

With ES6 you can use destructuring assignment to assign the numbers to a and c:

const b = 1
const [a, c] = b > 0 ? [1, 2] : [0, 1]

console.log(a, c)

Upvotes: 7

Related Questions