What are the template literals in ES6 ?
Template Literals are literal words in programming that are used to represent some kind of fixed value and template means a blueprint that can generate some entity, Therefore, the template literals are used to generate strings of a fixed value. These are delimited with the backticks ` `, We can inject the JavaScript expressions and strings inside it.
Syntax:
`Any string ${jsExpression} can appear here`
Example: In this example, we are illustrating a simple demo of template literals.
Javascript
<script> const str1 = `Hi, GeeksforGeeks Learner`; console.log(str1); const str = "GeeksforGeeks" ; const str2 = `Hi, ${str} Learner`; console.log(str2); </script> |
Output:
Hi, GeeksforGeeks Learner Hi, GeeksforGeeks Learner
Advantages: The usage of template strings has the following advantages:
1. Concatenating Strings: Template literals provide a much simpler way to concatenate two strings. Normally we use the “+” operator but with template literals, we can write whatever we want.
Example:
Javascript
<script> const strA1 = "Normal Javascript techniques" ; const strA2 = "are a little bit lengthy" ; console.log(strA1 + " " + strA2 + "." ); const strB1 = "Template literals" ; const strB2 = "make them simple" ; console.log(`${strB1} ${strB2}.`); </script> |
Output:
Normal Javascript techniques are a little bit lengthy. Template literals make them simple.
2. No need to use \n and \t escape sequences: Template literals reserve each type of space so we don’t need to tell explicitly for a new line or extra space.
Example:
Javascript
<script> console.log( "There will be a tab space after this" + "\t" + "end of string." ); console.log( "First Line" + "\n" + "Second Line" ); console.log(`There will be a tab space after this end of string.`); console.log(`First Line Second Line`); </script> |
Output:
There will be a tab space after this end of string. First Line Second Line There will be a tab space after this end of string. First Line Second Line
3. Combination of expressions and strings becomes easy: With template literals, we can inject any kind of expression which will be executed and determined at runtime inside strings.
Example 1: In this example, we are showing how a ternary operator can be used to generate a dynamic string with template literals.
Javascript
<script> let darkMode = true ; console.log( `The current background color is ${darkMode ? "#000000" : "#FFFFFF" }` ); </script> |
Output:
The current background color is #000000
Example 2: The simple illustration of how a mathematical expression can be inserted in template literals.
Javascript
const price = 5799.00; console.log( `The price of product is ${price} and after 16% discount it would cost ${price-price*16*0.01}` ); |
Output:
The price of product is 5799 and after 16% discount it would cost 4871.16
Please Login to comment...