Template Literals
Template literals, introduced in ES6, are a convenient way to create strings that contain dynamic content. They allow us to embed expressions directly into the string using placeholders enclosed in ${}
.
Syntax
To create a template literal, we use backticks () instead of single or double quotes to define the string. Within the template literal, we can include variables by wrapping them in
${}`.
JAVASCRIPT
1const name = 'John';
2const age = 25;
3
4// Using template literals
5console.log(`My name is ${name} and I am ${age} years old.`);
Advantages
Template literals offer several advantages over traditional string concatenation:
- Variable interpolation: We can directly embed variables in the string without the need for string concatenation.
- Multiline strings: Template literals preserve newlines, allowing us to create multiline strings without using escape characters.
- Expression evaluation: We can also include expressions within
${}
and have them evaluated directly within the string.
Template literals are a great tool for creating dynamic strings and improving code readability.
xxxxxxxxxx
// Template Literals
const name = 'John';
const age = 25;
// Using template literals
console.log(`My name is ${name} and I am ${age} years old.`);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment