OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 28

Template Literals and String Interpolation

By Ratan Updated: 16 Oct 2026

Construct multi-line strings and embed variable expressions using backticks (`${var}`).

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Build strings with expressions and line breaks

A template literal uses backticks. The ${...} placeholders evaluate expressions and insert their string representation. This improves readability when a message contains several values, but does not sanitize that message for HTML or another execution context.

const name = 'Asha';
const completed = 3;
const message = `${name} completed ${completed} lessons.`;
console.log(message); // Asha completed 3 lessons.

const summary = `Course: JavaScript
Completed: ${completed}
Next: Modules`;
console.log(summary);

Line breaks written inside the literal become part of the string. Indentation also becomes text, which matters in formatted output. Single or double quoted strings do not interpolate ${...} automatically.

Expressions, not arbitrary statements

const score = 82;
const result = `Result: ${score >= 40 ? 'Pass' : 'Needs practice'}`;
console.log(result); // Result: Pass

A placeholder contains an expression. If formatting requires complicated branching, compute a named value first rather than embedding a difficult nested expression into the string.

Escaping and safety

Escape a literal backtick or interpolation opener when needed. A backslash in an ordinary template literal still introduces escape sequences. String.raw exposes raw escape text in a tagged template, but is not an HTML sanitizer or an automatic security boundary.

const note = document.querySelector('#note');
if (note) note.textContent = `${name}: ${message}`;

textContent treats the composed string as text. Putting the same untrusted data into innerHTML could interpret markup. SQL parameters, safe URL construction and HTML text each require their own appropriate handling; interpolation alone provides none of those guarantees.

Practice

  1. Format a lesson title and duration in one message.
  2. Create a three-line plain-text progress report.
  3. Compare a backtick literal with a single-quoted string containing ${name}.
  4. Display a name containing angle brackets through textContent and confirm it remains text.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat