Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set multiple const values based on conditional

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?

like image 691
Toivo Säwén Avatar asked Aug 06 '26 06:08

Toivo Säwén


2 Answers

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)

like image 135
Sergii Shvager Avatar answered Aug 08 '26 19:08

Sergii Shvager


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)
like image 34
Ori Drori Avatar answered Aug 08 '26 19:08

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!