Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript conditional in template string

Is there a way to do conditional within a template string?

For example:

let x, y;

x = ...
y = ...

let templateString = `${x} ${y}`;

I don't want the space in the template string after x to be output if y is undefined. How would I achieve that with template string?

Is this the only way to do it?

 let templateString = `${x}${y ? ' ' + y : ''}`;
like image 387
Boon Avatar asked Nov 16 '18 17:11

Boon


1 Answers

What about

let x,y;

const templateString = [x,y].filter(a => a).join(' ');

What it does that it first puts your properties into an array [].

Then it filters the undefined items.

The last it creates a string of the array, by using join with a space.

This way either x or y can be undefined.

like image 159
baklazan Avatar answered Sep 21 '22 13:09

baklazan