2

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?

Toivo Säwén
  • 1,905
  • 2
  • 17
  • 33

3 Answers3

9

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)

Sergii Shvager
  • 1,226
  • 9
  • 14
4

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)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

I don't understand why everyone is so stuck at destructuring. Doesn't this work for you?

const a  = 1 ? 0 : -1,
      b = 0 ? 3 : -1;
ibrahim tanyalcin
  • 5,643
  • 3
  • 16
  • 22
  • 1
    Does not fulfil DRY, the conditional needs to be written twice here. – Toivo Säwén Mar 27 '20 at 11:34
  • 1. What if the two variables have independent conditions? 2. Noobish because you create an object in memory, and then cause 2 property access on top of 2 assignments and send it to garbage collection. DRY is not of any importance whatsoever in the situation of OP. – ibrahim tanyalcin Mar 27 '20 at 12:03
  • The question is specifcally related to if two values need to be set based on the same conditional. Otherwise I would use this solution. Cheers – Toivo Säwén Mar 27 '20 at 12:19