How do you interpolate variables inside JavaScript strings using template literals? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you interpolate variables inside JavaScript strings using template literals?

message-square
0

To interpolate variables and expressions inside JavaScript strings using template literals, enclose the string in backticks (`...`) rather than single or double quotes and place any variable or expression inside ${...} placeholders (const msg = Hello, ${userName}!;). Template literals evaluate any valid JavaScript expression inside ${...}—including arithmetic, ternaries, and function calls—and preserve literal line breaks and indentation across multiple lines without needing \n escapes or + concatenation.


1. Basic Variable and Expression Interpolation with `...` and ${...}

Wrap the string in backticks and put variable names or expressions inside ${...} so JavaScript converts the evaluated result to a string automatically:

// Interpolate variables, expressions, and function return values
function formatOrderSummary(customerName, itemCount, unitPrice) {
  const subtotal = itemCount * unitPrice;
  const discountNote = itemCount >= 3 ? "Bulk tier applied" : "Standard tier";

  return `Customer: ${customerName} | Items: ${itemCount} | Total: $${subtotal.toFixed(2)} (${discountNote})`;
}

// Example usage:
console.log(formatOrderSummary("Amina", 3, 12.5));
// "Customer: Amina | Items: 3 | Total: $37.50 (Bulk tier applied)"
  • Any expression works inside ${...}: You can embed math, ternary operators, property lookups, or helper function calls directly inside the placeholder.
  • No + operator needed: Interpolating values avoids messy quote-escaping and string-concatenation chains.

2. Multiline Strings Without Escape Sequences

Unlike single- or double-quoted strings, template literals allow actual newlines inside the string literal while still interpolating variables cleanly:

// Build a readable multiline message with embedded values
function buildReportHeader(serviceName, statusCode, timestamp) {
  return `Service: ${serviceName}
Status:  ${statusCode}
Updated: ${timestamp}`;
}

// Example usage:
console.log(buildReportHeader("AuthAPI", 200, "2026-11-29T11:01:00+05:00"));
  • Preserves newlines and spacing literally: Every line break inside the backticks becomes part of the resulting string.
  • Mind indentation in code: Leading spaces after a newline are included in the output string, so trim or align intentionally when building formatted text.

3. Escaping Backticks, ${}, and Using Tagged Templates

Inside a template literal, escape a literal backtick as \` or a literal placeholder sequence as \${...}, and pass a function before the opening backtick—known as a tagged template literal—when you want custom parsing or escaping of strings and interpolated values:

// Tagged template example that formats interpolated values safely
function upperCaseValues(strings, ...values) {
  return strings.reduce((acc, part, idx) => {
    const val = idx < values.length ? String(values[idx]).toUpperCase() : "";
    return `${acc}${part}${val}`;
  }, "");
}

// Example usage:
const role = "editor";
const literalExample = `Use \${variable} and \`backticks\` literally.`;
console.log(upperCaseValues`Assigned role: ${role}`); // "Assigned role: EDITOR"
console.log(literalExample);                          // "Use ${variable} and `backticks` literally."
  • Escape \ and ` when needed: Use \` for a literal backtick and \${ to prevent interpolation evaluation.
  • Tagged templates receive raw parts and values: The tag function gets an array of static string segments (strings) and the evaluated values separately for custom processing.