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?
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.
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.
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.
Use this:
let a = `test${conditional ? a : b} more text`;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With