Template literals in JavaScript
What are Template Literals?
Template literals (template strings) are string literals enclosed in backticks (`) that support embedded expressions, multi-line strings, and tagged templates. Introduced in ES6.
Basic Syntax
javascript
const name = "Alice";
const greeting = \`Hello, \${name}!\`;
console.log(greeting); // "Hello, Alice!"Expression Interpolation
javascript
const a = 10, b = 20;
console.log(\`Sum: \${a + b}\`); // "Sum: 30"
console.log(\`Type: \${typeof a}\`); // "Type: number"
console.log(\`Upper: \${"hello".toUpperCase()}\`); // "Upper: HELLO"
console.log(\`Ternary: \${a > 5 ? "big" : "small"}\`); // "Ternary: big"Multi-line Strings
javascript
// ❌ Old way
const old = "line 1\n" +
"line 2\n" +
"line 3";
// ✅ Template literal
const modern = \`line 1
line 2
line 3\`;Nesting Templates
javascript
const items = ["apple", "banana", "cherry"];
const html = \`
<ul>
\${items.map(item => \`<li>\${item}</li>\`).join("")}
</ul>
\`;Tagged Templates
A tagged template is a function that processes a template literal:
javascript
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i] !== undefined ? \`<b>\${values[i]}</b>\` : "";
return result + str + value;
}, "");
}
const name = "Alice";
const age = 25;
const result = highlight\`Name: \${name}, Age: \${age}\`;
// "Name: <b>Alice</b>, Age: <b>25</b>"Real-world Tagged Templates
javascript
// CSS-in-JS (styled-components)
const Button = styled.button\`
background: \${props => props.primary ? "blue" : "gray"};
color: white;
padding: 8px 16px;
\`;
// SQL query sanitization
const query = sql\`SELECT * FROM users WHERE id = \${userId}\`;
// Internationalization
const msg = i18n\`Hello, \${name}!\`;String.raw
String.raw is a built-in tagged template that returns the raw string without processing escape sequences:
javascript
String.raw\`Hello\nWorld\`; // "Hello\nWorld" (literal backslash-n)
\`Hello\nWorld\`; // "Hello
// World" (actual newline)
// Useful for regex or file paths
const path = String.raw\`C:\Users\Documents\file.txt\`;Important:
Template literals are the standard way to create strings in modern JavaScript. Use them for string interpolation, multi-line strings, and HTML generation. Tagged templates power libraries like styled-components and GraphQL query builders.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.