Javascript conditional in template string

It would look easier to read if you don't add the logic in the template:

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

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.


It's probably overkill for this small example, butTagged template functions provide a nice general solution that allow an amazing amount of flexibility while keeping your template strings clean. For example here's one that will remove text preceding an undefined variable in general:

function f(str ,...variables){
  return variables.reduce((res, v, i) => v ? res + str[i] + v: res, '')
}
let x, y, z;

x = "test"
y = "test2"

// both defined
console.log(f`${x} + ${y}`)

// only one:
console.log(f`${x} + ${z}`)

// random text:
console.log(f`${x} with ${z} and ${y}`)

Since it passes everything to a function, you can do almost any logic you want while still having readable strings. There's some documentation about halfway down the MDN Page on template literals.