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.
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.
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);