es6

Chapter 3: Mastering Template Literals in JavaScript (ES6)

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

  1. Create a string using traditional concatenation to show the name, age, and location of a person. Then rewrite it using a template literal.
  2. Use a template literal to generate a multiline invoice message that includes product name, quantity, price, and total using embedded expressions.
  3. Create a dynamic HTML structure using template literals with an object containing blog post data (title, content, tags). Inject it into the DOM.
  4. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *