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: PassA 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
- Format a lesson title and duration in one message.
- Create a three-line plain-text progress report.
- Compare a backtick literal with a single-quoted string containing ${name}.
- Display a name containing angle brackets through textContent and confirm it remains text.