How to Use Template Literals in JavaScript
Building strings with variables using template literals in JavaScript.
There are times when you need to build a string out of a few variables, like a
greeting with a user's name or a URL with an id on the end. Joining strings with
+ works, but it gets hard to read once you need spaces and punctuation in
between:
const message = "Hello " + firstName + ", you have " + count + " new messages."
Template literals make this a lot cleaner.
A template literal is a string wrapped in backticks that can include variables
and expressions with ${}.
Inserting Variables
Swap the quotes for backticks and wrap each variable in ${}:
const firstName = "Jim"const count = 3const message = `Hello ${firstName}, you have ${count} new messages.`// "Hello Jim, you have 3 new messages."
Now you can see the spaces and punctuation right in the string.
Using Expressions
Anything inside ${} is a JavaScript experssion, so you can do math, call a
function or use a ternary:
const price = 20const quantity = 3console.log(`Total: $${price * quantity}`)// "Total: $60"console.log(`You have ${count} ${count === 1 ? "message" : "messages"}`)// "You have 3 messages"console.log(`Hello ${firstName.toUpperCase()}`)// "Hello JIM"
The first $ in $${price * quantity} is just a dollar sign. Only ${ starts
an expression.
Multi-line Strings
With regular quotes you need \n for a new line. Template literals keep line
breaks exactly as you type them:
const address = `Jim Smith123 Main StreetSpringfield`
This comes in handy for building small chunks of HTML:
const user = { name: "Jim", role: "Sales" }const card = `<div class="card"><h2>${user.name}</h2><p>${user.role}</p></div>`document.querySelector("#users").innerHTML = card
Note: Be careful putting text a user typed into innerHTML. Use textContent
for anything you don't control.
Building URLs
Template literals are also the easiest way to build URLs with ids and query parameters:
const userId = 42const page = 2const url = `https://api.example.com/users/${userId}/posts?page=${page}`// "https://api.example.com/users/42/posts?page=2"
I use template literals any time a string has a variable in it.
Have some feedback on this post? .