JavaScript | template literals - GeeksforGeeks

23 Oct, 2019
Template Literal in ES6 provides new features to create a string that gives more control over dynamic strings. Traditionally, String is created using single quotes (‘) or double quotes (“) quotes. Template literal is created using the backtick (`) character.
Syntax:
var s=`some string`;
Multiline Strings: In-order to create a multiline string an escape sequence \n was used to give new line character. However, Template Literals there is no need to add \n string ends only when it gets backtick (`) character.
Example:<script>// Without template literalconsole.log('Some text that I want \non two lines!');  // With template literalconsole.log(`Some text that I wanton two lines!`);</script>
<script>// Without template literalconsole.log('Some text that I want \non two lines!');  // With template literalconsole.log(`Some text that I wanton two lines!`);</script>
Output:Some text that I want
on two lines!
Some text that I want
on two lines!
Some text that I want
on two lines!
Some text that I want
on two lines!
Expressions: To dynamically add values into new Template Literals expressions are used. The ${} syntax allows an expression in it that produces the value. This value can be a string stored in a variable or a computation operation.
${expression}
Example : The code below shows the use of expressions in template literals.<script>let principal = 1000;let noofyears = 1;let rateofinterest = 7;  let SI = `Simple Interest is ${(principal *            noofyears * rateofinterest)/100}`;alert("Simple Interest is" + SI);</script>
<script>let principal = 1000;let noofyears = 1;let rateofinterest = 7;  let SI = `Simple Interest is ${(principal *            noofyears * rateofinterest)/100}`;alert("Simple Interest is" + SI);</script>
Output:
Tagged Templates: One of the features of Template Literals is its ability to create Tagged Template Literals. Tagged Literal is written like a function definition, but the difference is when this literal is called. There is no parenthesis() to a literal call. An array of Strings are passed as a parameter to a literal.
Example 1:<script>  function TaggedLiteralEg(strings) {    document.write(strings);}  TaggedLiteralEg `GeeksforGeeks`;     </script>
<script>  function TaggedLiteralEg(strings) {    document.write(strings);}  TaggedLiteralEg `GeeksforGeeks`;     </script>
Output:GeeksforGeeks
GeeksforGeeks
Example 2: It is also possible to pass values to a tagged literal. This value can be a result of some expression or a value fetched from the variable. The code below shows the use of Tagged Literal.<script>function TaggedLiteralEg(strings, value, value2) {    document.write(strings);    document.write("<br>"+value2+"    "+value);      }  let text = 'GeeksforGeeks';TaggedLiteralEg`test ${text} ${2+3}`;    </script>
<script>function TaggedLiteralEg(strings, value, value2) {    document.write(strings);    document.write("<br>"+value2+"    "+value);      }  let text = 'GeeksforGeeks';TaggedLiteralEg`test ${text} ${2+3}`;    </script>
Output:test , ,
5 GeeksforGeeks
test , ,
5 GeeksforGeeks
Raw String: Raw method of template literal allows access of raw strings as they were entered, without processing escape sequences. In addition, the String.raw() method exists to create raw strings just like the default template function, and string concatenation would create.
Example:<script>var s=String.raw`Welcome to GeeksforGeeks Value of expression is ${2+3}`;document.write(s);</script>
<script>var s=String.raw`Welcome to GeeksforGeeks Value of expression is ${2+3}`;document.write(s);</script>
Output:Welcome to GeeksforGeeks Value of expression is 5
Welcome to GeeksforGeeks Value of expression is 5
Nested Templates: Templates can be nested if it contains multiple expression evaluation or multiple condition checking. Instead of using else if ladder this is readable and gives ease to the developer. The code below finds the maximum of three numbers using conditional operator and nested template literal.
Example:<script>function maximum(x, y, z) {var c = `value ${ (y>x && y>z) ? 'y is greater' :`${x>z ? 'x is greater' : 'z is greater'}` }`;return (c);}document.write(maximum(5, 11, 15)+"<br>");document.write(maximum(15, 11, 3)+"<br>");document.write(maximum(11, 33, 2)+"<br>");</script>                    
<script>function maximum(x, y, z) {var c = `value ${ (y>x && y>z) ? 'y is greater' :`${x>z ? 'x is greater' : 'z is greater'}` }`;return (c);}document.write(maximum(5, 11, 15)+"<br>");document.write(maximum(15, 11, 3)+"<br>");document.write(maximum(11, 33, 2)+"<br>");</script>                    
Output:value z is greater
value x is greater
value y is greater
value z is greater
value x is greater
value y is greater
javascript-basics
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?