DEV Community

Cover image for What are template literals ?
Ludivine A
Ludivine A

Posted on

What are template literals ?

Prior to ES6, you had to use single quotes (‘) or double quotes (“) to wrap a string, and that’s pretty much everything you could do with strings.

ES6 added the possibility to create “template literals” by wrapping string between backticks like this :

const myString = `My template literal`;
Enter fullscreen mode Exit fullscreen mode

You can use single and double quotes inside template literals :

const quote = `Say "hello" to my little friend!`;
Enter fullscreen mode Exit fullscreen mode

You can also create multi-line strings as follow :

const multilineString =
`Once upon a time, 
long,
long ago a king and queen ruled
over a distant land.`;
Enter fullscreen mode Exit fullscreen mode

String interpolation allows you to put variables inside your string. :

const count = 3;
const appleCount = `I have ${count} apples`;
console.log(appleCount) // "I have 3 apples"
Enter fullscreen mode Exit fullscreen mode

And you can also put a whole expression inside your string like so :

const amount = 3;
const total = `Total: ${(amount * 5).toFixed(2)}`;
console.log(total) // "Total: 15.00"
Enter fullscreen mode Exit fullscreen mode

Originally posted on my blog. Check out my instagram account to learn more about web development.

Top comments (0)