Member-only story
As developers, we deal with strings a lot — interpolating variables, building HTML, constructing SQL queries, formatting messages, and more. Stitching strings together with + concatenation works, but gets messy fast.
Enter JavaScript template literals — a cleaner string syntax leveraging backticks and placeholders to make building strings simple and readable again!
Let’s dive into how they work and creative ways to utilize them.
Basic Syntax
The core syntax for template literals wraps strings in backticks `` instead of quotes “” or ‘’:
const name = "Bob";
`Hello ${name}` // "Hello Bob"
We can interpolate any JS expressions inside ${} placeholders. The expressions get evaluated, toString()-ed, and inserted into the string.
This immediately makes templates more readable than concatenation. We also don’t need to worry about spacing and adding extra + signs:
const items = getCartItems();
const total = calculateTotal(items);
const message = `You have ${items.length} items in your cart for a total of $${total}`;