19

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 : ''}`;
Boon
  • 40,656
  • 60
  • 209
  • 315

7 Answers7

18

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.

baklazan
  • 814
  • 6
  • 13
13

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

let templateString = y ? `${x} ${y}` : `${x}`;
Darlesson
  • 5,742
  • 2
  • 21
  • 26
9

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.

Mark
  • 90,562
  • 7
  • 108
  • 148
  • 1
    @baklazan the function is passed an array of strings `str` which represent the text part of the template and an argument for variable (stored in `variables`) in the template. The `reduce` is looping through the variables and building up a string, by testing whether the variable is truthy. If it is it adds the corresponding string and variable to the returned string. – Mark Nov 16 '18 at 19:04
7

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.

dankobgd
  • 367
  • 3
  • 9
  • 31
7

An alternative, slightly terser approach using nested template literals.

`${x}${y ? ` ${y}` : ''}`
benvc
  • 14,448
  • 4
  • 33
  • 54
3

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

Just code
  • 13,553
  • 10
  • 51
  • 93
2

Even better

const templateString = `${x} ${y ?? ''}`.trim();
baklazan
  • 814
  • 6
  • 13