Read full article on the Infragistics blog
In ES6, two types of literals were introduced:
- Template Literals for string concatenation and expression embedding in a string
- Tagged Template Literals to tag the Template Literal in a function so the literal can be evaluated in the function
Let’s assume that you need to do the string concatenation with a dynamic expression or with the value of a variable. Take a look at the following code:
| var foo = 9; | |
| var result = `Result = ${foo}`; | |
| console.log(result); |
Here you see you’ll need to embed the value of variable foo in a string literal. In ES6, you can do this using Template Literals, as shown in the code listing above. Template Literals are mainly used for the following purposes:
- String concatenation
- To create multi line strings
- To embed expressions
- To use string interpolation
In the code above, we are embedding the expression foo in the string result. To use Template Literals:
- Template literals are created inside a back-tick (` `) character.
- In Template literals, placeholders are created using the ${expression} symbol. At run time, the expression will be evaluated and replaced in the placeholders.
- In template literals, the expression can be embedded using ${expression}. This is also called an expression interpolation.
Using Template literals, let us create some expression interpolation. Consider the following code:
| var num1 = 9; | |
| var num2 = 7; | |
| var result = `Result = ${num1 + num2} and twice of result = ${2 * (num1 + num2)}`; | |
| console.log(result); |
To create expression interpolation here, we are using the Template literal. You’ll also notice the string is broken into multiple lines. If required, you can created a nested template also.
Tagged Template Literals :
ES6 allows you to tag template literals, meaning you can parse that inside a function. So, if you use Tagged Template Literals, JavaScript will not immediately assign them to a variable, and rather parse them in a function
Read full article on the Infragistics blog
Discover more from Dhananjay Kumar
Subscribe to get the latest posts sent to your email.