Chapter 3: Template Literals in JavaScript (ES6)
In this section of ES6, you’ll learn about template literals โ a new way to work with strings more easily and cleanly.
Before ES6, developers used single ('
) or double ("
) quotes for string literals, which often led to messy concatenations and errors with embedded quotes.
ES6 solved this by introducing the backtick syntax ` `
that makes strings more readable, supports multiline content, and allows variable interpolation.
๐ Traditional JavaScript String Example
var str = "Hello this is an example of a template literal";
// Error if double quotes are nested:
var str = "Hello this is โexampleโ of the template literal";
โ Output: SyntaxError โ unexpected character due to quote nesting.
โ ES6 Template Literal Example
var str = `Hello this is โexampleโ of template literal`;
console.log(str);
โ๏ธ Output: Works fine with embedded quotes using backticks.
๐ Multiline Strings
Before ES6: Required manual line breaks using \n
var str = 'Multiline \n\
string';
console.log(str);
With ES6:
var str = `This is multi
Line string`;
console.log(str);
Now you can write multiline strings easily, with improved readability and flexibility.
๐ Variable Interpolation
The main feature that sets template literals apart is substitution, or string interpolation. Use ${variable}
inside the string to embed dynamic values.
let firstName = 'Rajesh';
let lastName = 'Kumar';
// Traditional string concatenation
console.log('Hi ' + firstName + ', ' + lastName);
// ES6 template literal
let fullName = `Hi ${firstName}, ${lastName}`;
console.log(fullName);
๐ฆ Real Example: HTML Templating with Template Literals
let content = { header: 'Welcome to ES6', excerpt: 'This is a short introduction of ES6', body: 'Here is the full content for ES6. And more content can be added here.', tags: ['es6', 'template literals', 'javascript'] }; let {header, excerpt, body: bodyText, tags} = content; let html = ` <article> <header> <h1>${header}</h1> </header> <section> <div>${excerpt}</div> <div>${bodyText}</div> </section> <footer> <ul> ${tags.map(tag => `<li>${tag}</li>`).join('\n')} </ul> </footer> </article>`; document.write(html);
This is a powerful way to dynamically inject structured HTML content using template literals.
๐งฎ Expressions Inside Template Literals
let price = 10.99;
let tax = 0.1;
var netPrice = `Net Price: โน${(price * (1 + tax)).toFixed(2)}`;
console.log(netPrice); // Output: Net Price: โน12.09
You can place entire expressions inside ${...}
to compute and embed results directly into your string!
๐ Assignments: Template Literals in ES6
- Create a string using traditional concatenation to show the name, age, and location of a person. Then rewrite it using a template literal.
- Use a template literal to generate a multiline invoice message that includes product name, quantity, price, and total using embedded expressions.
- Create a dynamic HTML structure using template literals with an object containing blog post data (title, content, tags). Inject it into the DOM.
- Declare a variable for tax and price. Use a template literal to compute and print the final price including tax. Try changing the values and observe the change in output.
๐ Summary
- Use
`backticks`
instead of single/double quotes. - Supports multiline strings without escape characters.
- Allows variable embedding and expressions with
${}
. - Cleaner syntax for dynamic content, especially HTML templates.