Javascript: Is there a better shorthand for conditional variable declaration?

Viewed 134

I have two variables foo& bar and I want to declare them based on a condition.

I have already shortened the code from this:

let foo = '';
let bar = '';

if (condition) {
  foo = 'hi';
  bar = 'bye';
} else {
  foo = 'bye';
  bar = 'hi';
}

To this:

const foo = condition ? 'hi' : 'bye';
const bar = !condition ? 'hi' : 'bye';

I still feel the code is repetitive with having to use ternary operator twice. Is there anyway I can shorten this code more? Thanks :)

3 Answers

You could take a destructuring with a single condition.

let [foo, bar] = condition ? ['hi', 'bye'] : ['bye', 'hi'];

Don't mind me, just trying to solve this simple problem in a complex way :)

let foo = 'hi';
let bar = 'bye';

[foo, bar] = !condition && [foo, bar].reverse() || [foo, bar];

Note: Nina Scholz's solution is perfect for your question.

Related