Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 625
Renzo Calla Avatar asked Aug 14 '17 14:08

Renzo Calla


People also ask

How do you write condition in template literals?

We can add placeholders in the template literals using ${}. This placeholder can have a constant or a variable, or an expression. Template literals are of two types: tagged template literals and untagged template literals.

How do you use Backticks in template literals?

In that case, the template literal is passed to your tag function, where you can then perform whatever operations you want on the different parts of the template literal. To escape a backtick in a template literal, put a backslash ( \ ) before the backtick. Dollar signs can be escaped as well to prevent interpolation.

What are template literals give an example?

Template literals (template strings) allow you to use strings or embedded expressions in the form of a string. They are enclosed in backticks `` . For example, const name = 'Jack'; console.


1 Answers

Use this:

let a = `test${conditional ? a : b} more text`; 
like image 187
lilezek Avatar answered Oct 14 '22 15:10

lilezek