In this tutorial, you will learn about JavaScript Template Literals (Template Strings) with the assistance of examples.
In this article, you will learn-
What are Template Literals?
Template Literals were presented with JavaScript ES2015 (ES6) to handle strings in a simpler and more readable way.
It allows us to embed expressions (expression interpolation) inside a string declaration, handle multiline strings and make “tagged template literals” which is a further advanced type of template literals.
Template literals are essentially the least way to improve your JavaScript code readability when working with Strings.
In JavaScript terminology, however, a template literal is an approach to concatenate strings while allowing embedded expressions and improving readability.
Template literals (template strings) allow you to use strings or implanted articulations as a string. They are encased in backticks ”. For instance,
const name = 'Salman'; console.log(`Hello ${name}!`); // Hello Salman!
Note: Template literal was presented in 2015 (otherwise called ECMAScript 6 or ES6 or ECMAScript 2015). A few browsers may not support the use of template literals. Visit JavaScript Template Literal support to learn more.
Template Literals for Strings
In the previous versions of JavaScript, you would use a single quote” or a double quote “” for strings. For instance,
const str1 = 'This is a string'; // cannot use the same quotes const str2 = 'A "quote" inside a string'; // valid code const str3 = 'A 'quote' inside a string'; // Error const str4 = "Another 'quote' inside a string"; // valid code const str5 = "Another "quote" inside a string"; // Error
To use similar quotations inside the string, you can use the escape character \.
// escape characters using \ const str3 = 'A \'quote\' inside a string'; // valid code const str5 = "Another \"quote\" inside a string"; // valid code
Instead of using escape characters, you can use template literals. For example,
const str1 = `This is a string`; const str2 = `This is a string with a 'quote' in it`; const str3 = `This is a string with a "double quote" in it`;
As should be obvious, the template literals not only make it simple to incorporate quotations as well as make our code look cleaner.
Multiline Strings Using Template Literals
Template literals likewise make it simple to write multiline strings. For instance,
Using template literals, you can replace
// using the + operator const message1 = 'This is a long message\n' + 'that spans across multiple lines\n' + 'in the code.' console.log(message1)
with
const message1 = `This is a long message that spans across multiple lines in the code.` console.log(message1)
The output of both these programs will be the equivalent.
This is a long message that spans across multiple lines in the code.
Expression Interpolation
Before JavaScript ES6, you would use the + operator to concatenate variables and articulations in a string. For instance,
const name = 'Salman'; console.log('Hello ' + name); // Hello Salman
With template literals, it’s somewhat simpler to incorporate variables and articulations inside a string. For that, we use the ${…} syntax.
const name = 'Salman'; console.log(`Hello ${name}`); // template literals used with expressions const result = `The sum of 4 + 5 is ${4 + 5}`; console.log(result); console.log(`${result < 10 ? 'Too low': 'Very high'}`)
Output
Hello Salman The sum of 4 + 5 is 9 Very high
The process toward allotting variables and articulations inside the template literal is known as interpolation.
Tagged Templates
Normally, you would use a function to pass arguments. For example,
function tagExample(strings) { return strings; } // passing argument const result = tagExample('Hello Salman'); console.log(result);
Notwithstanding, you can make tagged templates (that before like a function) using template literals. You use tags that allow you to parse template literals with a function.
The tagged template is written like a function definition. Be that as it may, you don’t pass parentheses () when calling the literal. For instance,
function tagExample(strings) { return strings; } // creating tagged template const result = tagExample`Hello Salman`; console.log(result);
Output
["Hello Salman"]
An array of string values are passed as the primary contention of a tag function. You could likewise pass the qualities and articulations as the remaining contentions. For instance,
const name = 'Salman'; const greet = true; function tagExample(strings, nameValue) { let str0 = strings[0]; // Hello let str1 = strings[1]; // , How are you? if(greet) { return `${str0}${nameValue}${str1}`; } } // creating tagged literal // passing argument name const result = tagExample`Hello ${name}, How are you?`; console.log(result);
Output
Hello Salman, How are you?
In this way, you can also pass multiple arguments in the tagged temaplate.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.