Template literals are strings written using backticks (`) that allow variables and expressions to be embedded directly. Introduced in ES6, they make strings more readable and support easy interpolation and multi-line text without complex concatenation.
- Use backticks (`) to embed variables and expressions directly in strings.
- Introduced in ES6, they support easy interpolation and multi-line strings.
let a='GFG'
console.log(`hello ${a}`)
- Embedding variables: Template literals like hello ${a} insert variable values directly into strings, producing output such as hello GFG.
- Cleaner concatenation: They avoid using +, making string creation more readable and easier to write.
Syntax:
`Text before ${variableOrExpression} text after`- Backticks (``): Used to define a template literal.
- ${}: Used to insert expressions inside the string, such as variables, function calls, or arithmetic operations
String Interpolation with Expressions
String interpolation lets you insert not just variables but also expressions, like math operations or function results, directly into a string.
let x = 5;
let y = 10;
console.log(`The sum of ${x} and ${y} is ${x + y}`);
- Expression evaluation: Inside ${}, expressions like x + y are evaluated, and the result is inserted into the string.
- Dynamic string creation: This technique allows you to dynamically create strings by combining variables and expressions, making the code cleaner and easier to read.
Multi-line Strings with Template Literals
Template literals allow you to create multi-line strings easily without needing escape characters like \n.
const s = `This is a multi-line
string that spans across
several lines.`;
console.log(s);
- Multi-line support: Template literals preserve line breaks, so the string appears exactly as it’s written, making multi-line strings easier to handle.
- No need for escape characters: You don’t need to use \n to break lines within the string; template literals automatically handle it.
Tagged Template Literals
Tagged template literals allow you to customize how the string is processed, providing more control over string creation.
function greet(strings, name) {
return `${strings[0]}${name.toUpperCase()}${strings[1]}`;
}
const name = 'gfg';
console.log(greet`Hello, ${name}!`);
- In this code the string Hello,! is passed as an array in which the 0th index contains Hello, and the second index contains !
- In the second parameter name is passed as gfg which is then converted to uppercase and then finally the concatenated content of the array and the value of the name parameter is combined and returned by the function.
Escaping Backticks and Dollar Signs
In JavaScript, if you need to include backticks or dollar signs inside template literals, you can escape them using a backslash (\).
const s = `This is a backtick: \` and this is a dollar sign: \$`;
console.log(s);
- Escaping Backticks: To include a backtick inside a template literal, you escape it with ``` to avoid ending the string.
- Escaping Dollar Signs: Similarly, if you need to include a dollar sign ($) without triggering an expression inside ${}, you escape it with \$.
JavaScript Template Literals
JavaScript Template Literals are mainly classified into 7 types based on their usage.
1. Multi-line Strings
Template literals support multi-line strings without special characters. This example displays a simple poem.
const poem = `Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you!`;
console.log(poem);
- Backticks allow multi-line strings naturally.
- Line breaks are preserved as written.
- The console.log outputs the formatted string.
2. Dynamic Expressions
Embedding arithmetic expressions within template literals. This example calculates the sum dynamically.
const a = 5, b = 10;
const result = `Sum of ${a} and ${b} is ${a + b}.`;
console.log(result);
- ${a + b} evaluates the sum of a and b.
- The result (15) is inserted into the string.
- The console.log outputs the complete sentence.
3. Tagged Templates
Tags process template literals directly, modifying how strings and placeholders are combined.
function tag(strings, ...values) {
return strings.reduce((acc, str, i) => acc + str + (values[i] || ''), '');
}
const output = tag`Hello, ${"Elis"}!`;
console.log(output);
- The function receives the static parts as an array and interpolated values separately.
- Returns a correctly formatted string without additional concatenation.
4. HTML Template
Template literals build HTML strings dynamically. This example creates an h1 element.
const title = "Welcome";
const html = `<h1>${title}</h1>`;
console.log(html);
- ${title} inserts the variable title into the string.
- The result is <h1>Welcome</h1>.
- Such templates are useful in dynamic web content generation.
5. Conditionals in Templates
Ternary operators evaluate conditions within template literals. This example displays a role based on a condition.
const isAdmin = true;
const userRole = `User role: ${isAdmin ? "Admin" : "Guest"}.`;
console.log(userRole);
- ${ isAdmin ? "Admin" : "Guest"} evaluates the condition.
- "Admin" is inserted when isAdmin is true.
6. Loops with Templates
Loops generate dynamic content within templates. This example creates a list of items.
const items = ["apple", "banana", "cherry"];
const list = `Items: ${items.map(item => `\n- ${item}`)}`;
console.log(list);
- items.map transforms each item into a string with \n- prefix.
- join combines the strings into one.
7. Embedding Functions
Template literals call functions directly. This example transforms text to uppercase.
const toUpper = str => str.toUpperCase();
const s = `Shouting: ${toUpper("hello")}`;
console.log(s);
- ${toUpper("hello")} invokes the function.
- The result ("HELLO") is inserted into the string.
- Template literals support embedding any valid expression.
