Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 947
Vinay Sharma Avatar asked Dec 11 '22 00:12

Vinay Sharma


1 Answers

You could take a destructuring with a single condition.

let [foo, bar] = condition ? ['hi', 'bye'] : ['bye', 'hi'];
like image 139
Nina Scholz Avatar answered Apr 06 '23 02:04

Nina Scholz