JavaScript Template Literals

Template literals, introduced in ES6 (ECMAScript 2015), provide an easy and powerful way to work with strings in JavaScript. They are enclosed by backticks (`) instead of single or double quotes.

Basic Syntax

Template literals use backticks (`) to define a string. This allows for easier string interpolation and multi-line strings.

Try yourself
        
            const greeting = `Hello, world!`;
console.log(greeting); // Outputs: Hello, world!
        
    

In this example, we create a simple string using template literals.


String Interpolation

Template literals allow for embedding expressions within strings using the ${} syntax.

Example: Simple Interpolation
Try yourself
        
            const name = 'John';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Outputs: Hello, John!
        
    

This example demonstrates how to use template literals for string interpolation.


Example: Expression Interpolation
Try yourself
        
            const a = 5;
const b = 10;
console.log(`The sum of a and b is ${a + b}`); // Outputs: The sum of a and b is 15
        
    

You can embed any valid JavaScript expression within template literals.


Multi-line Strings

Template literals make it easy to create multi-line strings without using escape characters.

Try yourself
        
            const poem = `Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.`;
console.log(poem);
        
    

This example shows how to create a multi-line string using template literals.


Tagged Templates

Tagged templates allow you to parse template literals with a function. The first argument of the function contains an array of string literals, while the remaining arguments are related to the expressions.

Try yourself
        
            function tag(strings, ...expressions) {
    return strings.reduce((acc, str, i) => acc + str + (expressions[i] || ''), '');
}
const name = 'John';
const message = tag`Hello, ${name}!`;
console.log(message); // Outputs: Hello, John!
        
    

This example demonstrates how to use tagged templates to process template literals.


Raw Strings

You can access the raw content of a template literal by using the String.raw method.

Try yourself
        
            const rawString = String.raw`This is a raw string with escaped characters: \\n`;
console.log(rawString); // Outputs: This is a raw string with escaped characters: \n
        
    

This example shows how to retrieve the raw string content of a template literal.


Important Notes

Here are some important notes and best practices when working with template literals in JavaScript:


Summary

Template literals are a powerful feature in JavaScript that simplify working with strings. They allow for easy string interpolation, multi-line strings, and more readable code. Understanding how to use template literals effectively can greatly enhance your JavaScript programming experience.