Show List

Template literals

Template literals are a feature introduced in ES6 (ECMAScript 2015) that allow for easier string interpolation and multiline strings in JavaScript. They are denoted by backticks (` `) instead of single or double quotes. Template literals also support expression interpolation, allowing you to embed JavaScript expressions directly within the string. Here's how they work with some examples:

  1. Basic usage of template literals:

const name = 'Alice'; const greeting = `Hello, ${name}!`; console.log(greeting); // Output: Hello, Alice!

In this example, the variable name is embedded within the template literal using ${} syntax. When the template literal is evaluated, the value of name is interpolated into the resulting string.

  1. Multiline strings with template literals:

const multiline = ` This is a multiline string. `; console.log(multiline); // Output: // This is a // multiline // string.

With template literals, you can define multiline strings without using explicit newline characters (\n). The string retains its formatting, including leading whitespace.

  1. Expression interpolation with template literals:

const a = 5; const b = 10; const result = `The sum of ${a} and ${b} is ${a + b}.`; console.log(result); // Output: The sum of 5 and 10 is 15.

You can also embed JavaScript expressions within template literals. These expressions are evaluated, and their results are included in the resulting string.

  1. Tagged template literals:

Tagged template literals are a more advanced feature that allows you to customize the behavior of template literals by tagging them with a function. The function receives the template literal's parts and interpolated values as arguments, giving you complete control over the resulting string. Here's a basic example:


function myTag(strings, ...values) { console.log(strings); // Array of string parts console.log(values); // Array of interpolated values } const name = 'Alice'; const age = 30; myTag`Hello, my name is ${name} and I am ${age} years old.`; // Output: // [ 'Hello, my name is ', ' and I am ', ' years old.' ] // [ 'Alice', 30 ]

In this example, the myTag function receives the parts of the template literal as the first argument (strings) and the interpolated values as the rest parameters (values). You can then process and manipulate these parts and values as needed.

Template literals offer a more readable and convenient way to work with strings in JavaScript, especially when dealing with dynamic content and multiline strings.


    Leave a Comment


  • captcha text