Back to course

Modern Strings: Template Literals and Interpolation (ES6)

JavaScript: The Complete '0 to Hero' Beginner Course

15. Template Literals (Backticks)

Template Literals, introduced in ES6, are defined using backticks (`) instead of quotes. They solve two major issues with traditional strings.

1. String Interpolation

Allows you to embed variables and expressions directly inside the string using the format ${expression}.

javascript let item = 'Laptop'; let price = 1200;

// Traditional concatenation: // let summary = 'The ' + item + ' costs $' + price + '.';

// Using Template Literals (much cleaner): let summary = The ${item} costs $${price * 1.05} (including tax).;

console.log(summary); // Output: The Laptop costs $1260 (including tax).

2. Multi-line Strings

Template literals allow you to define a string across multiple lines without using \n newline characters.

javascript let htmlContent = <div> <h1>Welcome!</h1> <p>This is a multi-line string.</p> </div>; console.log(htmlContent);

Best Practice: Always use template literals unless you specifically need single or double quotes.