Supercharge String Building with Template Literals

Forget Messy String Concatenation

Max N
2 min readFeb 21, 2024

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>
`;

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet