DEV Community

Cover image for ES6++: 4- Template Literals
Hasan Zohdy
Hasan Zohdy

Posted on

ES6++: 4- Template Literals

Introduction

In this article we will learn about Template literals which is one of the most important features of ES6.

What is a template literal?

A template literal is a string that allows embedded expressions. You can use multi-line strings and string interpolation features with them.

How to use template literals?

To use template literals you need to use backticks () instead of quotes (' or ") and you can use${}` to embed expressions.

`js
const name = 'Hasan';

const greeting = Hello ${name};

console.log(greeting); // Hello Hasan
`

Multi-line strings

You can use template literals to create multi-line strings.

js
const multiLine =
This is a
multi-line string`;

console.log(multiLine);// This is a
// multi-line string
`

Tagged template literals

You can use template literals with a function to create a tagged template literal.

`js
function tag(strings, ...values) {
console.log(strings); // [ 'Hello ', '!' ]
console.log(values); // [ 'Hasan' ]
}

tagHello ${name}!;
`

As you can see, we call the function that receives the template literal and pass the template literal as an argument, the function receives two arguments, the first one is an array of strings and the second one is an array of values.

The function call does not have parentheses after it, this is because the function is called as a tag of the template literal.

Raw strings

You can use raw property of the strings argument to get the raw strings.

`js
function tag(strings, ...values) {
console.log(strings.raw[0]); // Hello \n
}

tagHello \n;
`

Difference between template literals and single and double quotes

Let's see the major difference between template literals and single and double quotes.

  • Template literals allow you to use multi-line strings.
  • Template literals allow you to use string interpolation, AKA using variables, constants and function calls inside the string without the need of concatenation.
  • Template literals allow you to use tagged template literals.
  • Template literals allow you to use raw strings.

🎨 Conclusion

Overall, If you're going to use variables or functions inside a string, you should use template literals instead of single and double quotes.

☕♨ī¸ Buy me a Coffee ♨ī¸â˜•

If you like my articles and work, you can buy me a coffee, it will help me to keep going and keep creating more content.

😍 Join our community

Join our community on Discord to get help and support (Node Js 2023 Channel).

📚 Bonus Content 📚

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

Packages & Libraries

React Js Packages

Courses (Articles)

Latest comments (0)