Template strings, also known as template literals, are a convenient way to create strings in JavaScript. They allow you to embed expressions inside strings using backticks (`) instead of the traditional single (') or double (") quotes.

Features of Template Strings

  • Interpolation: You can embed expressions inside the template string using ${expression} syntax.
  • Multi-line Strings: Template strings can span multiple lines without the need for newline characters.
  • Tagged Templates: You can use tagged templates for more complex string manipulations.

Example

Here's an example that demonstrates how to use template strings:

const name = "John";
const age = 30;

console.log(`My name is ${name} and I am ${age} years old.`);

Output:

My name is John and I am 30 years old.

Syntax

To create a template string, you need to use backticks instead of single or double quotes:

let message = `Hello, world!`;

Interpolation

Interpolation allows you to insert expressions inside the template string. The expressions are evaluated and their values are included in the final string:

let username = "John";
let greeting = `Hello, ${username}!`;
console.log(greeting);

Output:

Hello, John!

Multi-line Strings

Template strings can span multiple lines without the need for newline characters:

let message = `This is a
multi-line string.`;
console.log(message);

Output:

This is a
multi-line string.

Tagged Templates

Tagged templates are a more advanced feature that allows you to perform custom string manipulations. They are defined using a tag function that takes the template string and its expressions as arguments:

function tag(strings, ...expressions) {
  // Manipulate the strings and expressions here
  return `${strings.raw[0]} - ${expressions[0]} - ${strings.raw[1]}`;
}

let result = tag`This is a tagged template ${1} with a number`;
console.log(result);

Output:

This is a tagged template 1 with a number

For more information on tagged templates, you can read the MDN documentation.

Conclusion

Template strings are a powerful feature in JavaScript that make string manipulation more convenient and flexible. They are widely used in modern JavaScript development and are an essential part of the language.

For more tutorials on JavaScript, visit our JavaScript tutorials page.