Renzo Calla
Renzo Calla

Reputation: 7696

Using conditionals inside template literals

I know there are more elegant ways to define a string with variables included, but if I want to add a conditional in pre ES6 I would do..

var a = "text"+(conditional?a:b)+" more text"

now with template literals I would do..

   let a;
   if(conditional) a = `test${a} more text`;
   else a = `test${b} more text`;

Is there a more elegant way to implement this conditional? is it possible to include if shortcut?

Upvotes: 52

Views: 52742

Answers (5)

Antonio Ooi
Antonio Ooi

Reputation: 1828

You can even do this:

${a || b}

Means: If a is null, use b.

Upvotes: 2

Nicolò Cavalli
Nicolò Cavalli

Reputation: 171

If you have a simple condition to check, use the ternary operator, as it as been said, but if you have more complex or nested conditions, just call a function in this way:

const canDrink = (age, hasToDrive) => {
  if (age >= 18 && !hasToDrive ) {
    return 'Yeah, no problem'
  } else if ( age >= 18 && hasToDrive ){
    return 'Maybe not that much'
  } else {
    return 'Not at all'
  }
}

console.log(`Can you drink tonight? ${ canDrink(21, true) }`) // Can you drink tonight? Maybe not that much

Upvotes: 1

Hussain
Hussain

Reputation: 138

let t1 = "hey";
let t2 = "there";
console.log(`${t1}${t2 ? `(${t2})` : ''}`);

Upvotes: 1

Remi
Remi

Reputation: 5367

You can also expand this a bit further and use placeholders inside such a conditional.

It really depends on the use case you have which is the most readable.

Some examples:

// example 1
const title = 'title 1';
const html1 = `${title ? `<h2>${title}</h2>` : '<h2>nothing 1</h2>'}`

document.getElementById('title-container-1').innerHTML = html1;

// example 2
const title2= 'title 2';
const html2 = `
	${title2 ? 
  	`<h2>${title2}</h2>` : 
  	"<h2>nothing 2</h2>"
  }`

document.getElementById('title-container-2').innerHTML = html2;

// example 3
const object = {
	title: 'title 3'
};

const html3 = `
	${(title => {
      if (title) {
        return `<h2>${title}</h2>`;
      }
	  	return '<h2>Nothing 3</h2>';
		})(object.title)
	  }
`;

document.getElementById('title-container-3').innerHTML = html3;
<div id="title-container-1"></div>
<div id="title-container-2"></div>
<div id="title-container-3"></div>

(source)

Upvotes: 22

lilezek
lilezek

Reputation: 7344

Use this:

let a = `test${conditional ? a : b} more text`;

Upvotes: 102

Related Questions