Gyaan

Template Literals

beginner ES6 strings template-literals

Template literals (introduced in ES6) are strings wrapped in backticks (`) instead of single or double quotes. They give us two main superpowers: expression interpolation and multi-line strings.

Expression interpolation

Instead of concatenating strings with +, we can embed expressions directly using ${expression}:

const name = "Manish";
const age = 25;

// Old way
const msg1 = "Hi, I'm " + name + " and I'm " + age + " years old.";

// Template literal — much cleaner
const msg2 = `Hi, I'm ${name} and I'm ${age} years old.`;

We can put any valid JavaScript expression inside ${} — not just variables:

console.log(`2 + 3 = ${2 + 3}`);           // "2 + 3 = 5"
console.log(`Uppercase: ${"hello".toUpperCase()}`); // "Uppercase: HELLO"
console.log(`Is adult: ${age >= 18 ? "Yes" : "No"}`); // "Is adult: Yes"

Multi-line strings

With regular quotes, creating a multi-line string requires \n. With backticks, we just press Enter and the line breaks are preserved:

// Old way
const old = "Line 1\n" +
            "Line 2\n" +
            "Line 3";

// Template literal
const html = `
  <div>
    <h1>Hello</h1>
    <p>World</p>
  </div>
`;

This is super handy when writing HTML strings, SQL queries, or any multi-line text in our code.

Tagged templates

This is a more advanced feature, but worth knowing about. A tagged template lets us parse template literals with a custom function. The function receives the string parts and the interpolated values separately:

function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    return result + str + (values[i] ? `<mark>${values[i]}</mark>` : "");
  }, "");
}

const name = "Manish";
const role = "developer";
const output = highlight`My name is ${name} and I'm a ${role}.`;
// "My name is <mark>Manish</mark> and I'm a <mark>developer</mark>."

Tagged templates are used in libraries like styled-components (CSS-in-JS) and graphql-tag (GraphQL queries). We might not write tagged templates ourselves every day, but it is good to understand how they work when we see them in the wild.

In simple language, template literals are just a better way to write strings. Use backticks, drop in variables with ${}, and enjoy multi-line strings without \n. Once we start using them, we will never want to go back to string concatenation.