Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple operations in ternary operator

Is it possible to have multiple operations within a ternary operator's if/else?

I've come up with an example below, probably not the best example but I hope you get what I mean.

var totalCount = 0;
var oddCount = 0;
var evenCount = 0;
for(var i = 0; i < arr.length; i++) {
  if(arr[i] % 2 === 0) {
    evenCount ++;
    totalCount ++;
  } else {
    oddCount ++;
    totalCount ++;
  }
}

into something like:

var totalCount = 0;
var oddCount = 0;
var evenCount = 0;
for(var i = 0; i < arr.length; i++) {
  arr[i] % 2 === 0? evenCount ++ totalCount ++ : oddCount ++ totalCount ++;
  }
}
like image 358
Apswak Avatar asked Oct 26 '16 15:10

Apswak


1 Answers

You can use the comma operator to execute multiple expressions in place of a single expression:

arr[i] % 2 === 0? (evenCount++, totalCount++) : (oddCount++, totalCount++);

The result of the comma operator is the result of the last expression.

But yeah, don't use the conditional operator for side effects.

like image 190
Felix Kling Avatar answered Oct 16 '22 09:10

Felix Kling