Difficulty: Beginner
What are template literals in JavaScript? What features do they provide over regular strings?
Template literals are string literals enclosed in backticks (`) that provide:
1. String interpolation - embed expressions with ${expression} 2. Multiline strings - no need for \n or string concatenation 3. Tagged templates - process template literals with a function 4. Raw strings - access raw string content without escape processing
const name = "Alice";
const age = 25;
// String interpolation
console.log(`Hello, ${name}! You are ${age} years old.`);
// Expression interpolation
console.log(`Next year: ${age + 1}`);
console.log(`Is adult: ${age >= 18 ? "Yes" : "No"}`);
// Multiline strings
const html = `
<div>
<h1>${name}</h1>
<p>Age: ${age}</p>
</div>
`;
console.log(html);
Template literals allow embedding any JS expression inside ${} and naturally support multiline content.
// Building URLs
const userId = 42;
const url = `/api/users/${userId}/posts`;
console.log(url);
// Conditional messages
const items = 3;
const msg = `You have ${items} item${items !== 1 ? "s" : ""} in cart`;
console.log(msg);
// Nesting templates
const isLoggedIn = true;
const greeting = `${isLoggedIn ? `Welcome back, ${name}!` : "Please log in"}`;
console.log(greeting);
Template literals make string building much cleaner than concatenation.
Template Literals, String Interpolation, Multiline Strings, ES6