DEV Community

Cover image for Template literals (Template strings)
Sudhakar V
Sudhakar V

Posted on

Template literals (Template strings)

JavaScript Template Literals (Template Strings)

Template literals, introduced in ES6 (ES2015), are an improved way to work with strings in JavaScript. They provide several powerful features over traditional string literals.

Basic Syntax

Template literals use backticks (`) instead of single or double quotes:

const message = `Hello World`;
Enter fullscreen mode Exit fullscreen mode

Key Features

1. Multi-line Strings

No need for \n or concatenation:

const multiLine = `
  This is 
  a multi-line
  string
`;
Enter fullscreen mode Exit fullscreen mode

2. String Interpolation

Embed expressions using ${expression} syntax:

const name = 'Alice';
const age = 25;

// Traditional way
const greeting1 = 'Hello ' + name + ', you are ' + age + ' years old';

// With template literal
const greeting2 = `Hello ${name}, you are ${age} years old`;
Enter fullscreen mode Exit fullscreen mode

3. Expression Evaluation

Expressions inside ${} are evaluated:

const a = 5;
const b = 10;
console.log(`The sum is ${a + b}`); // "The sum is 15"
Enter fullscreen mode Exit fullscreen mode

4. Tagged Templates

Advanced feature for custom string processing:

function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => 
    `${result}${str}<span class="highlight">${values[i] || ''}</span>`, '');
}

const name = 'John';
const age = 30;
const highlighted = highlight`Hello ${name}, you are ${age} years old`;
Enter fullscreen mode Exit fullscreen mode

Practical Examples

1. HTML Templates

const user = {
  name: 'Sarah',
  role: 'Developer'
};

const html = `
  <div class="user-card">
    <h2>${user.name}</h2>
    <p>Role: ${user.role}</p>
    <p>Joined: ${new Date().getFullYear() - 2}</p>
  </div>
`;
Enter fullscreen mode Exit fullscreen mode

2. Complex Expressions

const items = ['Coffee', 'Tea', 'Milk'];
const total = items.length;

const list = `
  <ul>
    ${items.map(item => `<li>${item}</li>`).join('')}
  </ul>
  <p>Total items: ${total}</p>
`;
Enter fullscreen mode Exit fullscreen mode

3. Conditional Rendering

const isLoggedIn = true;
const welcomeMessage = `
  Welcome back!
  ${isLoggedIn ? 'You have 3 new notifications' : 'Please log in'}
`;
Enter fullscreen mode Exit fullscreen mode

Advantages Over Traditional Strings

  • Cleaner syntax for string concatenation
  • Better readability for complex strings
  • No need to escape single/double quotes inside the string
  • Support for multi-line strings without workarounds[TBD]

REFERENCES- Template Literals - MDN Web Docs -https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Top comments (0)