Template literals are a more convenient way to write strings compared to the previous ES5 syntax.
They are also sometimes called template strings.
The ES5 way of writing:
function getMessage() {
const year = new Date().getFullYear();
return "This year is " + year +" year."
}
getMessage();
Writing with template literals:
Use `` (backticks)
with $
and {}
.
It’s similar to Ruby’s string interpolation #{}
.
function getMessage() {
const year = new Date().getFullYear();
return `This year is ${year}.`
}
getMessage();
When to use: