Template Literals

Template literals are a modern way to work with strings in JavaScript. They allow easier string creation with embedded expressions and multi-line formatting.

Illustration of template_literals
Illustration of template_literals

💡 What are Template Literals?

Strings enclosed by backticks `...` instead of single or double quotes. They support:

  • Embedding variables and expressions with ${...}
  • Multi-line strings without escape characters

Basic Syntax

📌 Deep Dive: Creating a Template Literal

JAVASCRIPT
const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting);
Output
Hello, Alice!

Embedding Expressions

You can include any JavaScript expression inside ${...}, not just variables.

📌 Deep Dive: Expression Evaluation

JAVASCRIPT
const a = 5;
const b = 10;
console.log(`Sum: ${a + b}`);
console.log(`Uppercase: ${"hello".toUpperCase()}`);
Output
Sum: 15
Uppercase: HELLO

Multi-line Strings

Template literals preserve new lines and spacing without needing escape characters.

📌 Deep Dive: Multi-line Template Literal

JAVASCRIPT
const message = `This is line one.
This is line two.
And this is line three.`;
console.log(message);
Output
This is line one.
This is line two.
And this is line three.
Comparison: Template Literals vs Traditional Strings
FeatureTemplate LiteralsTraditional Strings
DelimitersBackticks `...`Single '...' or Double "..." quotes
Expression EmbeddingYes, using ${...}No, use concatenation
Multi-line StringsSupported directlyNeed escape sequences \
ReadabilityCleaner for complex stringsHarder with concatenation

⚠️ Important

Template literals must use backticks (`), not single or double quotes. Using wrong quotes disables expression evaluation.

Use template literals whenever you want readable, flexible strings with embedded values or multi-line formatting.