1

Is it good practice that assigning value to variables inside conditional operator ? This is about conditonal/turnery operator not about if statement

 a===1 ? (b=2) : (b=0)

I am getting lint warning when using this method.

Abidh
  • 457
  • 2
  • 5
  • 13

1 Answers1

3

No, using an assignment as an assignment is rarely a good idea - code is much easier to read and understand when conditions only test conditions, rather than when those conditions also have side-effects. In this case, you can fix it putting 2 and 0 as the expressions on the right:

const b = a === 1 ? 2 : 0;

The only time I think an assignment inside a conditional might possibly look cleaner than the alternative is when iterating over a global regular expression manually to extract matched groups (this is not using the conditional operator, but the principle is similar):

const regex = /\w(?=(\w))/g;
const str = 'foo';

let match;
while (match = regex.exec(str)) {
  console.log(match[1]);
}

Alternatives, without assigning inside the while condition, are:

// Requires while(true):
const regex = /\w(?=(\w))/g;
const str = 'foo';

while (true) {
  const match = regex.exec(str);
  if (!match) {
    break;
  }
  console.log(match[1]);
}

or

// A bit WET:
const regex = /\w(?=(\w))/g;
const str = 'foo';

let match = regex.exec(str);
while (match) {
  console.log(match[1]);
  match = regex.exec(str);
}

But that might be opinion-based.

Note that (ab)using the conditional operator as a replacement for if/else is common to see in minified code, but that's perfectly fine, because minified code isn't meant to be read, only parsed. It's also a valid technique in code golf.

If you want to assign to multiple variables inside a conditional, you can use destructuring:

const a = 689;
const [b, c] = a === 1 ? [2, 1] : [0, 3];
console.log(c);

Or, if the variables are strongly related, which sounds likely, it would probably be better to use an object (or array) instead of multiple standalone variables:

const a = 689;
const obj = a === 1 ? { b: 2, c: 1 } : { b: 0, c: 3 };
console.log(obj);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 1
    consider this situation a===1 ? (b=2,c=1):(b=0,c=3) The reason I followed this is because, based on a single condition I want to assign values to two variables. If I follow this, I could avoid one condition checking – Abidh May 09 '19 at 06:13
  • 1
    You could use destructuring: `const [b, c] = a === 1 ? [2, 1] : [0, 3];` You could also use a plain `if/else` statement if using `const` isn't required (though `const` is preferable when possible). If `b` and `c` are strongly related variables, like if they represent similar things, I'd recommend using an object or array instead of two separate variables – CertainPerformance May 09 '19 at 06:17
  • can you write this as the answer, I feel this is more appropriate. I will accept – Abidh May 09 '19 at 06:22