Template literals
Text templates in backticks: insert values with ${} and span multiple lines.
- Returns
- A new string with the values of the expressions inserted in place of
${...}. A tagged template returns whatever the tag function returns.
Example
#const name = 'Mia'
const points = 120
const goal = 200
console.log(`Hi, ${name}! You have ${points} pts.`)
console.log(`${goal - points} pts left to the goal.`)Definition and usage
#Template literals are written in backticks `. Inside, you can insert any JavaScript expression in ${...}: a variable, a calculation, a function call, or a conditional operator. The result gets converted to text and inserted right there.
A template can span multiple lines. Newlines and indentation from the code end up in the string exactly as written, so you don’t need \n or string concatenation with +. That’s convenient for building messages and HTML fragments.
A function name written right before a template, e.g. highlight`You have ${points} pts`, creates a tagged template. The function receives the constant text pieces and the inserted values separately, so it can process them however it likes. The built-in String.raw tag returns the text without interpreting escape sequences like \n.
Syntax
#`text`
`text ${expression} text`
`line 1
line 2`
tag`text ${expression}`More examples
#const course = 'JavaScript'
const lessons = 12
const card = `Course: ${course}
Lessons: ${lessons}
Status: ${lessons > 10 ? 'long' : 'short'}`
console.log(card)const tasks = ['Variables', 'Loops']
const list = `<ul>${tasks.map((task) => `<li>${task}</li>`).join('')}</ul>`
console.log(list)function highlight(strings, ...values) {
return strings.reduce((result, text, i) => {
const value = i < values.length ? `[${values[i]}]` : ''
return result + text + value
}, '')
}
const player = 'Jack'
const exp = 45
console.log(highlight`Player ${player} earned ${exp} XP`)
console.log(String.raw`C:\new\folder`)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Don’t insert user data into HTML without sanitizing it. A template doesn’t escape
<and>, so code like that opens the door to XSS attacks. Insert text throughtextContentinstead. - In a multi-line template, the code’s indentation becomes part of the string. If that gets in the way, start further lines at the left edge, or join an array of lines with
join("\n"). - An object inserted with
${}turns into[object Object]. Insert a specific field instead, or useJSON.stringify().
Related entries
#- String.prototype.replace()Returns a new string in which the first match of a pattern (or all matches, with the g flag) has been replaced with other text.
- String.prototype.padStart()Pads a string on the left with the given text until it reaches the specified length. Perfect for leading zeros.
- ? :The conditional (ternary) operator returns one of two values depending on a condition, in one short expression.
- Array.prototype.join()Joins the array’s elements into a single string with a chosen separator.
- String.prototype.split()Splits a string into an array of pieces based on a separator: a character, a string, or a regular expression.
Spotted a mistake or missing an example? Write to us.