I want to set multiple values based on a conditional. This code would work:
let a;
let b;
if (fooBar) {
a = "foo";
b = "bar";
} else {
a = "baz";
b = "Hello world!";
}
But I am trying to adhere to FP (immutable variables) and DRY principles.
For one variable, I would do this:
const a = fooBar
? "foo"
: "baz";
Can I somehow set multiple variables this way?
I would say nothing wrong with using let overall, however the answer to your question is:
const [a, b] = fooBar ? ["foo", "bar"] : ["baz", "Hello world!"]
In this case array destructuring can be used. So we create variables to access array item by index (a is #0, b is #1)
Use a ternary to generate an object or array with the required values, then use destructuring to assign them:
const fooBar = false
const { a, b } = fooBar ?
{ a: 'foo', b: 'bar' }
:
{ a: 'baz', b: 'Hello world!' }
console.log(a, b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With