lost9123193
lost9123193

Reputation: 11030

Having a 1 line conditional update other variables in Javascript

Not sure if this is possible but is there a way this can be simplified to one line without using an if else call? i.e update all variables when a certain condition is met?

const dogStatus = present ? "bark" : "beep";
const catStatus = present ? "meow" : "meep";
const fishStatus = present ? "blub" : "bleeboop";

Upvotes: 0

Views: 31

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

The conditional operator and destructuring can do this:

const [dogStatus, catStatus, fishStatus] = present ? ['bark', 'meow', 'blub'] : ['beep', 'meep', 'bleeboop'];

For the sake of code organization, I'd strongly consider if having just a single variable instead of multiple standalone variables would be possible, I'd prefer it in most situations:

const status = present
  ? { dog: 'bark', cat: 'meow', fish: 'blub' }
  : { dog: 'beep', cat: 'meep', fish: 'bleeboop' };

Upvotes: 5

Related Questions