MakeW3web

JavaScript Template literals

Template literals, introduced in ES6 (ECMAScript 2015), are a new way of creating and working with strings in JavaScript. They provide an easy and convenient syntax for creating multiline strings and embedding expressions within strings. Template literals are enclosed by backticks (```) instead of single or double quotes.

  1. Multiline strings:

Template literals allow you to create multiline strings without the need for concatenation or escape sequences.

const multilineString = `This is a multiline
string created with a
template literal.`;
console.log(multilineString);
  1. Interpolation:

Template literals support string interpolation, which means you can embed expressions, variables, and other JavaScript code directly within the string using the `${expression}` syntax.

const name = 'John';
const age = 30;
const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting); // "Hello, my name is John and I am 30 years old."
  1. Tagged template literals:

Tagged template literals allow you to create custom functions, called "tags," that can be used to modify the output of a template literal. A tag function receives an array of string literals and an array of expressions as its arguments and can manipulate them before returning the final string.

function customTag(strings, ...values) {
  let result = '';

  for (let i = 0; i < strings.length; i++) {
    result += strings[i];
    if (i < values.length) {
      result += values[i].toUpperCase();
    }
  }

  return result;
}

const firstName = 'John';
const lastName = 'Doe';
const taggedString = customTag`Hello, my name is ${firstName} ${lastName}.`;
console.log(taggedString); // "Hello, my name is JOHN DOE."

Template literals are a powerful and convenient feature of modern JavaScript, allowing you to create multiline strings, embed expressions directly within strings, and even define custom functions to modify the output of a template literal. They can make your code more readable and maintainable by reducing the need for concatenation and escape sequences.

Was this page helpful?