Module 32 // Core JavaScript

Template Literals (Advanced)

Module Objective

Tagged templates, raw strings

Mental Model Realtime Simulation

INTERACTIVE_CANVAS
Editor_Pane
Loading...
Console_Output
Waiting for output...

Practical Code Examples

// Example 1
// 1. Clean HTML Generation
const user = { name: "Subhajit", role: "Admin" };

const html = `
  <div class="user-card">
    <h2>${user.name}</h2>
    <p>Role: ${user.role}</p>
  </div>
`;

console.log(html);
💡 Template literals make building HTML strings or complex message blocks incredibly readable by preserving whitespace and newlines.
// Example 2
// 2. Logic inside ${}
const price = 100;
const tax = 0.15;

const total = `Total: $${(price * (1 + tax)).toFixed(2)}`;
console.log(total); // "Total: $115.00"
💡 You can put any valid JavaScript expression inside `${}`—not just variables, but function calls and math operations too.
// Example 3
// 3. Tagged Template Power
function highlight(strings, ...values) {
  return strings.reduce((acc, str, i) => {
    return `${acc}${str}<strong>${values[i] || ''}</strong>`;
  }, '');
}

const name = "JSViz";
const msg = highlight`Welcome to ${name}!`;
console.log(msg); // "Welcome to <strong>JSViz</strong>!"
💡 Tagged templates allow you to parse template literals with a function. This is how libraries like `styled-components` or `lit-html` work.

Engine & Memory Architecture

String Construction

1. Evaluation Phase:

  • The engine evaluates every expression inside ${} first in the Stack.
  • It then concatenates the static parts and dynamic results into a new String object.

2. Constant Strings:

  • Static parts of the template are stored in the String Pool in the Heap to save memory.

3. Performance:

  • While template literals are slightly more complex to parse than single quotes, modern engines optimize them heavily. They are generally faster than manual concatenation using + for multiple variables.