Back to: JavaScript Tutorial For Beginners and Professionals
JavaScript Template Literals with Examples
In this article, I am going to discuss JavaScript Template Literals with Examples. Please read our previous article where we discussed JavaScript TypedArray. String in JavaScript are collections of one or more characters. Working with strings is one of the core skills all developers need. JavaScript provides a number of ways for manipulating and working with strings. At the end of this article, you will understand the following pointers.
- What are Template Literals in JavaScript?
- Features of Template Literals in JavaScript
- Where to use JavaScript Template Literals or why do we need them?
- How to Create JavaScript Template Literals
- Creating multi-line strings in JavaScript
- Creating String Interpolation in JavaScript
- Expression Interpolation in JavaScript
- Creating Nesting Templates in JavaScript
- Tagged Template Literals in JavaScript
- Where to use Tagged Template in JavaScript?
- Raw Strings in JavaScript
What are Template Literals in JavaScript?
JavaScript ES6 introduced two types of literals: Template Literals and Tagged Template Literals to tag Template Literals. In this article, we will learn both of them in depth. In ES6, two types of literals were introduced:
- Template Literals are string literals with support for string concatenation and expression embedding (enclosed) in a string
- Tagged Template Literals (short: tagged templates) to tag the Template Literal in a function so the literal can be evaluated in the function. In other words, are function calls whose parameters are provided via template literals.
Template Literals in JavaScript
You might wonder, what Template Literals are, and more importantly, why do we even need them? Template Literals are a fast and widely adopted new way of defining strings.
JavaScript ES6 provides new features Template Literal to create a string with more control and easy-grip over dynamic strings. Template literals are string literals that allow embedding expression. We can use multi-line string and string interpolation features with them. Prior to the ES6 specification, they were called “template strings”.
Template literals is an expression interpolation (means -the insertion of something of a different nature into something else.) for single and multiple-line strings.
- Single line strings: Traditionally, String is created using single quotes (‘) or double quotes (“) quotes. Template literals are enclosed by the backtick (`…`) character instead of double or single quotes. It is a key (`) situated below the ESC key on the keyboard.
- Multiline Strings: Prior to ES6, In-order to create a multiline string an escape sequence \n was used to give a new line character and the \ character at the end of a line to be able to write multi-line strings. However, in Template Literals there is no need to add \n string ends only when it gets backtick (`) character.
The expression can be indicated by the dollar sign and curly braces ${…} or ” ${expression} “.
Features of Template Literals in JavaScript
- We can declare strings with ` (backticks), in addition to “ and ‘
- Template literals are a new way of string literal that provides features to use multiple line strings and expression embedding.
- Strings wrapped in backticks (`) character are template literals
- Template literals can be multiline.it makes multi-line string simpler
- We can interpolate variables and expression using the ${} syntax
- Expression or placeholder can be indicated by the dollar sign and curly braces ” ${expression} “.
- Template literals allow interpolation like `Olx.com have ${rating}` where the rating is a variable
- We can use any valid JavaScript expressions in the interpolation, such as `${5 * 6}` or `${getUser()}`
- We can use tagged templates to change how expressions are interpolated
- Add a function name funcName prefix to funcName `John, ${value1} and ${value2}`
- funcName is called once with the template, …expressions
- template is [‘John ‘, ‘ and ‘, ”] and expressions is [value1, value2]
- The result of funcName becomes the value of the template literal
- Possible use cases include input sanitization of expressions, parameter parsing, etc.
- Tagged templates are a new way to write CSS in JavaScript.
Where to use JavaScript Template Literals or why do we need them?
- For creating String interpolation (means- the insertion of something into something else.)
- For string concatenation
- For creating multi-line strings
- Expression embedding
- For creating tagged templates
Creating JavaScript Template Literals
As mentioned earlier, template literals use backticks (`) to create string instead of single (‘) or double (“) quotes. While using backticks we can easily use the single or double quotes in template literals without escaping it. When we create a string and if a string contains backticks we can escape it using a backward slash (\).
Syntax: const str=`This is test string`
Example: JavaScript Template Literals example
<html> <head> <title>JavaScript Template literals Example</title> </head> <body> <script> //Before ES6 const myString = 'I am a Normal string before ES6'; console.log("Before ES6 string: ", myString) //With ES6 const templateLiterals = `I am a Template Literals in ES6`; console.log("With ES6 template string: ", templateLiterals) console.log("With ES6 template string length: ", templateLiterals.length); // 29 console.log("With ES6 template string type is: ", typeof templateLiterals);// string //template literals using backticks with single quotes const templateLiteralswithSingleQuotes = `Here's a Template Literals in ES6`; console.log("template literals using backticks with single quotes: ", templateLiteralswithSingleQuotes); //template literals with backticks can be escape with \ //const templateLiteralswitBackticks = `Im a Template Literals in ES6 \ `instead of double quotes`; </script> </body> </html>
Output:
Creating multi-line strings in JavaScript:
Prior to ES6, In-order to create a multiline string an escape sequence \n was used to give the new line character and the \ character at the end of a line to be able to write multi-line strings. Also, putting the backward slash (\) after the newline character (\n) shows the continuation of the string instead of the newline. However, In Template Literals there is no need to add \n string ends only when it gets backtick (`) character.
Syntax:
const mutliString = `This is Template literal
with multi-line
in ES6`;
Example1: JavaScript Template literals multi-line Example
<html> <head> <title>JavaScript Template literals multi-line Example</title> </head> <body> <script> //Before ES6-for creating multi-line strings const oldString = 'Im a Normal string\n\ with multi-line\n\ before ES6'; console.log("Before ES6 multi-line string: ", oldString) //With ES6- for creating multi-line strings use (trim()) at the end is just used to remove space const templateLiteralMutliLineString = `This is Template literal with multi - line in ES6`.trim(); console.log("With ES6 template literals multi-line string: ", templateLiteralMutliLineString) </script> </body> </html>
Output:
The following code returns the chunk of HTML code interpolated with some variables of the blogPost object. Note that we use the object de-structuring technique to assign the properties of the post object to individual variables: title, intro, body, and tags.
Example2: JavaScript Template literals multi-line Example with a chunk of HTML interpolated
<html> <head> <title>JavaScript Template literals multi-line Example with chunk of HTML Interpolated</title> </head> <body> <script> var blogPost = { title: 'Hello Template Literals', intro: 'Template literals makes String interpolation easier ', body: 'it sanitized HTML', tags: ['es6', 'template-literals', 'javascript'] } let { title, intro, body, tags } = blogPost; var postHtml = `<article> <header> <h1>${title}</h1> </header> <section> <div>${intro}</div> <div>${body}</div> </section> <footer> <ul> ${tags.map(tag => `<li>${tag}</li>`).join('\n ')} </ul> </footer>`; console.log("With ES6 template literals multi-line with HTML interpolated with variables: ", postHtml); </script> </body> </html>
Output:
Creating String Interpolation in JavaScript
Template literals provide the simplest way to interpolate variables as well as expressions into strings. ES6 introduces a new way of outputting variable values in strings. In template Literals, the variable can be embedded using ${variable}. Which is also called a string interpolation
Syntax: ${variable}
Example: JavaScript Template literals string Interpolation Example
<html> <head> <title>JavaScript Template literals string Interpolation example</title> </head> <body> <script> //Interpolation before ES6 we used concatenation technique let name = "Anurag" let oldStringMsg = "Welcome " + name + "!"; console.log("Before ES6 Interpolation string: ", oldStringMsg) //Interpolation with ES6- for removing length concatenation technique let personName = " Anurag" const templateLiteralStringMsg = `Welcome ${personName}!`; console.log("With ES6 template literals Interpolation string: ", templateLiteralStringMsg); </script> </body> </html>
Output:
Creating Expression Interpolation in JavaScript
In template Literals, the expression can be embedded using ${expression}. This is also called an expression interpolation. As we saw template literals are enclosed by the backtick (` `) character instead of single or double-quotes. The ${expression} is a placeholder and can conclude any expression which will get evaluated and inserted into the template literal.
Syntax: ${expression}
Example1: JavaScript Template literals expression Interpolation Example
<html> <head> <title>JavaScript Template literals expression Interpolation Example</title> </head> <body> <script> //Interpolation before ES6 we used concatenation technique let a = 100 let b = 200 let oldStringSum = "The Sum is " + (a + b); console.log("Before ES6 expression Interpolation: ", oldStringSum) //Interpolation with ES6- for removing length concatenation technique let x = 100 let y = 200 let templateLiteralStringSum = `The Sum is ${x + y}`; console.log("With ES6 template literals expression Interpolation: ", templateLiteralStringSum); </script> </body> </html>
Output:
Example2: JavaScript Template literals Expression Interpolation Example
<html> <head> <title>JavaScript Template literals expression Interpolation Example</title> </head> <body> <script> //Interpolation with ES6- for removing length concatenation technique let employee = { firstName: "Anurag", lastName: "JavaScript", position: "Developer" }; let template = `Name:${employee.firstName} ${employee.lastName} Position:${employee.position}`; console.log("With ES6 template literals expression Interpolation: ", template); </script> </body> </html>
Output:
Creating Nesting Templates in JavaScript
Templates can be nested if the template contains multiple expressions or multiple conditions. Rather than using the if-else scope, the nested template gives a more user-friendly readable way to setup the strings. In most cases, nesting a template is the easiest readable way to have to customize strings. Within a backtick template, it is easy to allow inner backticks by using them inside a placeholder ${ } within the template.
Example1: JavaScript Template literals Nesting Template Example
<html> <head> <title>JavaScript Template literals Nesting Template Example</title> </head> <body> <script> //Before ES6 var firstName = "Anurag"; var lastName = "JavaScript"; var oldNestingString = "Hello! My name is " + firstName + ' ' + lastName; console.log("Before ES6 Nesting Template string :", oldNestingString); //With ES6 var fName = "Anurag"; var lName = "JavaScript"; var templateLiteralsNestingString = `Hello! ${`My name is ${fName} ${lName}`}`; console.log("With ES6 template literals Nesting Template string :", templateLiteralsNestingString); </script> </body> </html>
Output:
Example2: JavaScript Template literals Nesting Template Example
<html> <head> <title>JavaScript Template literals Nesting Template Example</title> </head> <body> <script> //with ES6 function largeNum(a, b, c) { var z = `value ${(b > a && b > c) ? 'b is greater' : `${a > c ? 'a is greater' : 'c is greater'}`}`; return (z); } document.write("With ES6 Template literals Nesting template is: " + "<br>"); document.write(largeNum(3, 10, 15) + "<br>"); document.write(largeNum(15, 11, 3) + "<br>"); document.write(largeNum(11, 33, 9) + "<br>"); </script> </body> </html>
Output:
Tagged Template Literals in JavaScript
A Tagged template provides a new way to parse template literals with a function that allows controlling the string creation. They consist of two parts: a tag function and a template literal.
Tagged Template literals (short: tagged templates) are functions call whose parameters are provided via template literals. A more advanced form of template literals is tagged template literals. With them, we are able to modify the output of template literals using a function.
In Tagged Template Literals, the function gets the following parameters:
- The first argument contains an array of string literals (“Hello”, “to” in the below sample)
- The second and each argument after the first one, are the values of the processed substitution expressions. (“10” and “20” here in the below sample)
In the end, the function returns manipulated string. The function name can be anything we want. The way of the tagged template working is that we put the name of the function that we want to execute before the string template. Tagged Literal is written like a function definition. The only difference is that when we called the literal there is no need for parenthesis () to literal call that means instead of function() we have to called
Where to use Tagged Template in JavaScript?
Tagged templates in JavaScript are one feature that seems less useful at first, but actually, it’s used by lots of popular libraries around like Style Component or Apollo the GraphQL client /server lib. So, it’s essential to understand how it works. In Style components, template tags are used to define CSS strings. Style components are used in REACT JS.
Syntax: functionName `tagged template literal string`
Example1: JavaScript Tagged Template literals Example
<html> <head> <title>JavaScript Tagged Template literals Example</title> </head> <body> <script> //sample1 function TaggedLiteralEg(strings) { document.write("Tagged template literals simple msg: ", strings + "<br>"); } TaggedLiteralEg`DotNetTutorials JavaScript`; //function name with template literals //sample2 let Subject = "JavaScript"; let lang = "Scripting"; function myFunc(strings) { return strings; } document.write(myFunc`This is ${Subject} and ${lang}`); </script> </body> </html>
Output:
In the above sample code, the first parameter in the tag function, myFunc, is a variable that contains an array of strings in the template literals After the array variable, all other parameters will contain the values passed to the template literal. As we have not passed processed values hence the output is coming as “This is , and ,”
Suppose we want to pass a template literal, perform some manipulation, and return a result. To do that, we can tag the template literal to function as shown below.
Example2: Function returning with/without an array of strings in template literals
<html> <head> <title>JavaScript Tagged Template literals Example</title> </head> <body> <script> //sample1- Function returning without array of strings in template literals let Subject = "JavaScript"; let lang = "Scripting"; function myFunc(strings, value1, value2) { console.log(value1 + " " + value2); return strings } console.log("Sample-1 Function returning without array of strings in template literals: " ); console.log(myFunc`This is ${Subject} and ${lang}`); //sample2- with array of strings in template literals function tagFunc(strings, name, country) { console.log(strings[0]); //hey console.log(strings[1]);// welcome to console.log(strings[2]); // empty string, undefined console.log(name); // Shagufta console.log(country); // India return ''; } const name = "Anurag"; const country = "India"; console.log("Sample-2 Function returning array of strings in template literals: "); const result = tagFunc`hey ${name} welcome to ${country}`; console.log(result); </script> </body> </html>
Output:
In the above sample code, the first parameter in the tag function, tagFunc, is a variable containing an array of strings in the template literals. After the array variable, all other parameters will contain the values passed to the template literal.
Example3: Tagged Template literals using the spread operator
<html> <head> <title>JavaScript Tagged Template literals using spread operator Example</title> </head> <body> <script> var x = 10, y = 20; function tagFunction(strings, ...parameters) { console.log(strings[0]); //Hey sum is console.log(strings[1]);// product is console.log(strings[2]); // empty string, undefined "" console.log(parameters[0]); // 30 console.log(parameters[1]); // 200 return 'bingo'; } console.log("Tagged Template literals using spread operator: "); const result = tagFunction`Hey sum is ${x + y} product is ${x * y}`; console.log(result); </script> </body> </html>
Output:
Raw Strings in JavaScript
The string.raw property available on the function first arguments of tagged template literals, allows us to access the raw strings as they were entered. The Raw string can be define using string.raw() method. This method displays the raw strings without identifying the backward slash(\) character. It is the same as the default template function.
Example1: JavaScript Tagged Template literals using spread operator for Raw strings
<html> <head> <title>JavaScript Tagged Template literals using spread operator for Raw strings Example</title> </head> <body> <script> var x = 10, y = 20; function tagFunction(strings, ...parameters) { console.log(strings[0]); //Hey sum is console.log(strings[1]);// product is console.log(strings[2]); // empty string, undefined "" console.log(parameters[0]); // 30 console.log(parameters[1]); // 200 console.log("The raw strings are") console.log(strings.raw[1]) return strings; } console.log("Tagged Template literals using spread operator for raw strings: "); const result = tagFunction`Hey sum is ${x + y} product is ${x * y}`; console.log(result); </script> </body> </html>
Output:
Example2: JavaScript Tagged Template literals Raw string using string.raw() method
<html> <head> <title>JavaScript Tagged Template literals Raw string using strig.raw() method Example</title> </head> <body> <script> var rawText = String.raw`Welcome \n Hello \n world!` console.log("Raw string using string.raw: ", rawText) </script> </body> </html>
Output:
In the next article, I am going to discuss JavaScript Object Literals with Examples. Here, in this article, I try to explain the JavaScript Template Literals with Examples. I hope this JavaScript Template Literals with Examples article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about the JavaScript Template Literals article.