JavaScript Template Literals
Template literals are strings written with backticks that support embedded expressions and multi-line text.
Template Literals
Template literals are a modern way to write strings, introduced in ES6. Instead of quotes, they use backticks. Their two standout features are string interpolation — dropping variables and expressions directly into text — and native support for strings that span multiple lines.
To insert a value, wrap it in a dollar sign and curly braces: ${ }. JavaScript evaluates whatever is inside the braces and converts the result to a string. This replaces the older, harder-to-read style of joining pieces with the + operator.
Interpolation vs concatenation
<!DOCTYPE html>
<html>
<body>
<h2>Interpolation vs concatenation</h2>
<script>
let name = "Sam";
let role = "developer";
// Old style with the + operator
let oldWay = "Hi " + name + ", the " + role;
// Template literal
let newWay = `Hi ${name}, the ${role}`;
console.log(newWay); // Hi Sam, the developer
</script>
</body>
</html>Expressions inside placeholders
<!DOCTYPE html>
<html>
<body>
<h2>Expressions inside placeholders</h2>
<script>
let price = 20;
let quantity = 3;
console.log(`Total: $${price * quantity}`); // Total: $60
let user = { first: "Ada", last: "Lovelace" };
console.log(`Name: ${user.first.toUpperCase()} ${user.last}`);
// Name: ADA Lovelace
</script>
</body>
</html>A template literal keeps every line break you type between the backticks. This makes it easy to build multi-line output such as HTML fragments or formatted messages without messy \n escape sequences.
Multi-line strings
<!DOCTYPE html>
<html>
<body>
<h2>Multi-line strings</h2>
<script>
let title = "Report";
let html = `
<div>
<h1>${title}</h1>
<p>Generated today</p>
</div>
`;
console.log(html);
</script>
</body>
</html>- Use backticks (`), not straight quotes.
- Embed values with ${expression}.
- Line breaks between the backticks are preserved.
- To include a literal backtick or ${, escape it with a backslash.