InterviewHubPRO
Section Overview
Q497

Question 497 of 521

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

95%
JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

What are tagged template literals and their practical uses?

Tagged template literals allow you to parse template literals with a function, giving you full control over the interpolation process.

javascript
 function tag(strings, ...values) {
   console.log(strings); // Array of string literals
   console.log(values);  // Array of interpolated values
   return 'processed';
 }

 const name = 'John';
 const age = 30;
 const result = tag`Hello ${name}, you are ${age} years old`;
 // strings: ['Hello ', ', you are ', ' years old']
 // values: ['John', 30]

Practical use cases:

  1. HTML escaping for security:
javascript
    function html(strings, ...values) {
      return strings.reduce((result, str, i) => {
        const value = values[i - 1];
        const escaped = String(value)
          .replace(/&/g, '&')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;');
        return result + escaped + str;
      });
    }

    const userInput = '<script>alert("XSS")</script>';
    const safe = html`<div>${userInput}</div>`;
  1. Internationalization (i18n):
javascript
    function i18n(strings, ...values) {
      // Look up translation for the template
      return translate(strings, values);
    }

    const greeting = i18n`Hello ${userName}!`;
  1. SQL query building:
javascript
    function sql(strings, ...values) {
      // Safely escape values to prevent SQL injection
      return {
        text: strings.reduce((query, str, i) => 
          query + str + (i < values.length ? `$${i + 1}` : ''),
        ''),
        values: values
      };
    }

    const query = sql`SELECT * FROM users WHERE id = ${userId}`;
  1. Styled-components (CSS-in-JS):
javascript
    const Button = styled.button`
      background: ${props => props.primary ? 'blue' : 'white'};
      color: ${props => props.primary ? 'white' : 'blue'};
    `;