What Are Template Literals?

Template literals (also called template strings) are a powerful feature introduced in ES6 that provide a more readable and expressive way to work with strings in JavaScript. They use backticks (`) instead of single or double quotes and offer several advantages over traditional string handling methods.

Key Point: Template literals allow for string interpolation, multi-line strings, and tagged templates, making string manipulation much cleaner and more efficient.

Basic Syntax Comparison

Different Ways to Create Strings

// Using single quotes
const singleQuotes = 'I am not new to JavaScript';

// Using double quotes
const doubleQuotes = "I am not new to JavaScript";

// Using backticks (template literals - ES6)
const backticks = `I am not new to JavaScript`;

console.log(singleQuotes);
console.log(doubleQuotes);
console.log(backticks);

String Interpolation with Template Literals

One of the most powerful features of template literals is the ability to embed expressions directly within the string using the ${expression} syntax.

Variable Interpolation Example

let a = 90;

// Traditional approach (concatenation)
const oldWay = 'Value of a is ' + a + '.';

// With template literal
const newWay = `Value of a is ${a}.`;

console.log(oldWay); // "Value of a is 90."
console.log(newWay);  // "Value of a is 90."

Expression Evaluation

let x = 5;
let y = 10;

// Mathematical operations
console.log(`The sum of x and y is ${x + y}.`);
// Output: "The sum of x and y is 15."

// Ternary operations
console.log(`Is x greater than y? ${x > y ? 'Yes' : 'No'}.`);
// Output: "Is x greater than y? No."

// Function calls
const getName = () => 'John Doe';
console.log(`Hello, ${getName()}!`);
// Output: "Hello, John Doe!"

Multi-line Strings

Template literals preserve whitespace and line breaks, making it easy to create multi-line strings without using escape characters.

Multi-line String Example

// Traditional approach (using concatenation)
const oldMultiLine = 'This is line one.\n' +
                   'This is line two.\n' +
                   'This is line three.';

// With template literal
const newMultiLine = `This is line one.
This is line two.
This is line three.`;

console.log(oldMultiLine);
console.log(newMultiLine);

/* Both output:
This is line one.
This is line two.
This is line three.
*/

Tagged Templates

Tagged templates allow you to parse template literals with a function, giving you more control over string processing.

Tagged Template Example

// Define a tag function
function highlight(strings, ...values) {
    let result = '';
    strings.forEach((string, i) => {
        result += string;
        if (values[i]) {
            result += `${values[i]}`;
        }
    });
    return result;
}

let name = 'Alice';
let age = 30;

// Use the tag function
const highlighted = highlight`Hello, my name is ${name} and I am ${age} years old.`;
console.log(highlighted);
// Output: "Hello, my name is Alice and I am 30 years old."

Comparison Table: Traditional Strings vs Template Literals

Feature Traditional Strings Template Literals
Variable Interpolation Requires concatenation with + operator Embed expressions directly with ${}
Multi-line Strings Requires \n escape sequence Preserves line breaks and formatting
Readability Can become messy with complex strings Clean and maintainable syntax
Tagged Templates Not available Custom processing with tag functions

Best Practices

  • Use template literals for strings that contain variables or expressions
  • Use template literals for multi-line strings
  • Use traditional quotes for very simple strings without variables
  • Consider using tagged templates for complex string processing
  • Be consistent with your string style throughout your codebase