Summary
`Hello world`
`Hello ${variableName}`
`The answer is ${1 + 1}`
`This is a
multi-line string`
Details
Template literals are another way of writing strings. They make it easier to add placeholder values inside the string that can be replaced. They also allow you to add JavaScript expressions inside the string as well.
To write a simple template literal, wrap your text in backticks instead of single or double quotes.
`Hello world`
You can add a placeholder inside your template literal by writing a dollar sign and curly braces: ${}
. You can place the name of a variable inside the curly braces, like this:
let variableName = 'John';
`Hello ${variableName}`
// result: 'Hello John'
You can also add mathematical expressions inside the placeholder, like this:
`The answer is ${1 + 1}`
// result: 'The answer is 2'
Multi-line strings
It’s possible to create multi-line strings using a template literal, like this:
`This is a
multi-line string`
To create a multi-line string using a normal string, you’d have to use \n
to create a new line, like this:
'This is a\nmulti-line string'
"This is a\nmulti-line string"
Demo
Exercises
Try the following statements in the console:
`Hello world`
let name = 'John'
`Hello ${name}`
`The answer is ${1 + 1}`
`This is a
multi-line string`