Skip to content

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 : ''}`;

Answer

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.