Nearby lessons
3 of 22JavaScript Template String
📌 What are Template Strings?
Template strings in JavaScript (also known as template literals) allow you to create strings that are easier to read and write, especially when combining variables and expressions. Unlike regular strings defined with single or double quotes, template strings use backticks (`) and support interpolation and multi-line text.
1️⃣ Basic Syntax
Template strings are enclosed in backticks (`) instead of single ('') or double quotes (""). You can insert variables or expressions using ${expression} inside the string.
- Use backticks (`) instead of quotes
- Interpolate variables or expressions using
${} - Supports multi-line strings without escape characters
| Attribute | Value | Description |
|---|---|---|
Backticks | `Hello, ${name}!` | Syntax used to define template strings |
${expression} | ${2 + 2} | Embed an expression or variable inside a string |
Code Example
2️⃣ Multi-line Strings
Template strings allow multi-line strings without needing \n or concatenation.
- Create multi-line strings easily
- No need for newline characters or string concatenation
| Attribute | Value | Description |
|---|---|---|
Multi-line String | `Line 1\nLine 2` | String spans across multiple lines as written |
Code Example
🚫 Without Template String
Using traditional string concatenation with + makes the code longer and harder to read.
Code Example
✅ With Template String
Using backticks and ${} expressions makes string construction more readable and intuitive.
Code Example
🧠 Template String with Function
You can embed function calls inside template strings to dynamically build more complex messages.