As developers, we spend a lot of time working with strings — combining, manipulating and outputting text. In JavaScript, building strings used to involve messy concatenation with plus signs or ugly newlines in quotes. Luckily, modern template literals provide a clearer syntax for crafting strings.
Let’s explore how template literals can simplify JavaScript string building!
Basic Template Syntax
Template literals use backticks `` and ${} placeholders instead of quotes and plus signs:
// Template literal
const name = "Kyle";
const greeting = `Hello ${name}`;
// Old string concatenation
const greeting = "Hello " + name;
This keeps things readable without trailing additions.
We can also use ${expressions} inside the placeholders:
const items = 3;
const order = `You have ${items} items in your order`;
And even call functions inside!
Multi-line Strings
Things get even better with multi-line strings. Template literals allow newlines without \\n hacks:
const html = `
<div>
<h1>Hello World!</h1>
</div>
`;