Javascript conditional in template string

Viewed 14403

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

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

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

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.

An alternative, slightly terser approach using nested template literals.

`${x}${y ? ` ${y}` : ''}`

technically you can nest these template strings, its not pretty but this works

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

i would use the solution from the first comment though.

You can also use functions inside expressions

Here is an example of it

let x, y;

x = 'test'
y = undefined;

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

function fn(value1,value2) { return value2? (value1 + ' ' + value2) : value1 }
console.log('when undefined =',`${fn(x,y)}`);


x = 'test'
y = 'test1';

console.log('when not undefined = ',`${fn(x,y)}`);

reference

Even better

const templateString = `${x} ${y ?? ''}`.trim();
Related