Search code examples
javascriptecmascript-6functional-programmingimmutabilitydry

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?


Solution

  • 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)