Template Literals
Overview
Template Literals, introduced in ES6 (2015), revolutionized how developers work with strings in JavaScript. Before ES6, combining strings and variables required clumsy concatenation using the + operator, which often led to spacing errors.
Template literals use backticks ( `) instead of single or double quotes. This unlocks two massive features:
1. String Interpolation: You can inject variables and expressions directly into the string using the ${expression} syntax.
2. Multi-line Strings: You can write strings spanning multiple lines without needing escape characters like \n.
Syntax
const firstName = "Kartik";
const age = 22;
// The Old Way (Concatenation)
const oldStr = "My name is " + firstName + " and I am " + age + " years old.";
// The Modern Way (Template Literal)
const newStr = `My name is ${firstName} and I am ${age} years old.`;const price = 10;
const tax = 0.2;
// You can run math expressions inside the ${} block!
const total = `Total Cost: $${price * (1 + tax)}`;
// Multi-line strings maintain their formatting exactly as typed
const htmlTemplate = `
<div class="card">
<h2>${firstName}</h2>
<p>Welcome to the platform!</p>
</div>
`;Common Pitfalls
- Using standard quotes (
'or") instead of backticks () when trying to use interpolation. If you write"Hello ${name}", JavaScript will literally print the characters${name}` instead of evaluating the variable.
Interview Questions
Yes. The ${} syntax evaluates any valid JavaScript expression. This means you can call functions, run ternary operators, or perform math calculations directly inside the string. Example: ${user.getAge() > 18 ? 'Adult' : 'Minor'}.
Real-World Example
Constructing dynamic API endpoint URLs based on function parameters.
async function fetchUserProfile(userId) {
// Using a template literal to inject the ID into the URL
const response = await fetch(`https://api.example.com/users/${userId}`);
return response.json();
}Check Your Knowledge
Test your understanding of Template Literals with these quick questions.