Template Literals (Basics)
Template Literals (Basics) in JavaScript
Before ES6 (2015), creating dynamic strings or multi-line text in JavaScript required clumsy string concatenation using the plus operator (+) and escape characters (\n). Template Literals (written with backticks `` ... ``) revolutionized string formatting in JavaScript.
1. What are Template Literals?
Template literals are string literals delimited by backticks (` `) instead of quotes (' or "`).
They provide two monumental superpowers:
- 1String Interpolation: Embedding variables and expressions directly inside strings with
${expression}. - 2Native Multi-Line Strings: Preserving newlines and indentation without
\n.
2. String Interpolation (${...})
Instead of messy concatenation:
The Old Way (ES5):
The Modern Way (Template Literals):
Any Valid JavaScript Expression Inside ${...}:
You can perform mathematical calculations, function calls, or ternary logic inside ${}:
3. Multi-Line Strings Made Simple
Before template literals, multi-line HTML templates required concatenation on every line:
The Old Way:
With Template Literals:
Every newline, space, and indentation is preserved exactly as written!
4. Escaping Backticks Inside Template Literals
If you need to include a literal backtick inside a template literal, escape it with \`:
Practice Quiz
const x = 5; const y = 3; console.log(${x} + ${y} = ${x + y});?\n escape characters?${...} in a template literal?Defining and Calling Functions
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Common String Methods | Defining and Calling Functions |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.