JavaScript ES6+ Features: Template Literals Explained with Examples
Code example showing JavaScript template literal syntax using backticks and variables
Introduction
Before ES6, JavaScript developers struggled with complex string concatenation using the +
operator and newline characters (\n
). With the introduction of template literals in ES6 (ECMAScript 2015), JavaScript gained a cleaner, more readable way to handle strings — especially when embedding variables or writing multi-line text.
In this article, we'll explore what template literals are, how they work, and how they simplify everyday coding in JavaScript.
Template literals (also called template strings) are string literals enclosed by backticks (`
) instead of single ('
) or double ("
) quotes.
They allow you to:
Embed expressions directly in the string
Create multi-line strings without using escape characters
Include variables easily using the ${}
syntax
const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Alice!
Unlike traditional strings, you don’t need to use the +
operator to concatenate values.
You can embed any JavaScript expression inside ${}
.
const a = 5;
const b = 10;
console.log(`The sum of a and b is ${a + b}.`);
// Output: The sum of a and b is 15.
No need for \n
or string concatenation:
const poem = `Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you.`;
console.log(poem);
You can insert function calls, arithmetic, or even ternary expressions inside ${}
.
const score = 90;
const result = `You ${score > 80 ? "passed" : "failed"} the test.`;
console.log(result); // Output: You passed the test.
const title = "JavaScript Template Literals";
const html = `
<div>
<h1>${title}</h1>
<p>This is a dynamic HTML block.</p>
</div>
`;
document.body.innerHTML = html;
const user = "Shubham";
const loginTime = new Date().toLocaleTimeString();
console.log(`[${loginTime}] - ${user} logged in.`);
JavaScript also supports tagged templates, which allow you to customize how template literals are processed.
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => `${result}${str}<b>${values[i] || ""}</b>`, "");
}
const name = "John";
const city = "Delhi";
const sentence = highlight`Hello, my name is ${name} and I live in ${city}.`;
console.log(sentence);
// Output: Hello, my name is <b>John</b> and I live in <b>Delhi</b>.
Template literals are supported in all modern browsers:
✅ Chrome 41+
✅ Firefox 34+
✅ Edge 12+
✅ Safari 9+
✅ Node.js 4+
If you're targeting legacy browsers like Internet Explorer, consider transpiling your code using Babel.
Template literals are one of the most powerful and developer-friendly features introduced in ES6. They make string handling simpler, cleaner, and more expressive. Whether you're creating dynamic messages, formatting HTML, or handling multi-line strings, template literals can significantly enhance your JavaScript code.