Template Literals β Backticks and Variable Interpolation
After completing this topic
You will know how to create strings cleanly using backticks and the ${} syntax.
Limitations of Quotes
const name = "Alice";
const age = 25;
const msg = "Hello, " + name + "! You are " + age + " years old.";To insert a variable into a string, you have to concatenate it with the + operator. When there are many variables, opening and closing quotes and adding plus signs becomes cumbersome, making it difficult to read and write.
Backticks and $
const name = "Alice";
const age = 25;
const msg = `Hello, ${name}! You are ${age} years old.`;Enclose the string with backticks (`) and insert the variable inside ${}. The combination of quotes and plus signs disappears. This is called a Template Literal. It was added in ES6 (2015).
Inside ${}, not only variables but also expressions can be used:
const price = 15000;
const quantity = 3;
console.log(`Total: ${price * quantity}won`);
// Total: 45000won
console.log(`Status: ${age >= 18 ? "adult" : "minor"}`);
// Status: adultFunction calls are also possible:
console.log(`Upper: ${name.toUpperCase()}`);
// Upper: ALICEMulti-line Strings
To create multi-line strings with regular quotes, you need to insert \n:
const old = "Line 1\nLine 2\nLine 3";Backticks recognize line breaks as they are:
const html = `
<div>
<h1>${title}</h1>
<p>${content}</p>
</div>
`;This is especially useful when creating HTML templates. Indentation is also preserved.
Key Points
Template literals are a syntax that uses backticks and
${}to insert variables and expressions into strings. It is easier to read than string concatenation (+), and it also naturally supports multi-line strings.