Boon
Boon

Reputation: 41490

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

Upvotes: 19

Views: 23571

Answers (7)

baklazan
baklazan

Reputation: 821

Even better

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

Upvotes: 2

Mark
Mark

Reputation: 92440

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.

Upvotes: 9

Just code
Just code

Reputation: 13801

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

Upvotes: 3

benvc
benvc

Reputation: 15130

An alternative, slightly terser approach using nested template literals.

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

Upvotes: 7

dankobgd
dankobgd

Reputation: 408

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.

Upvotes: 7

baklazan
baklazan

Reputation: 821

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.

Upvotes: 18

Darlesson
Darlesson

Reputation: 6162

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

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

Upvotes: 13

Related Questions