Learn ES6 Features

Jihen Barhoumi
3 min readJan 30, 2021

--

This article is the second article of ES6 series , I will explain to you what are Template Literals and what they are used for in ES6

Template literals are used for two things :

  • Writing strings with line breaks
  • Concatenating strings
  1. Writing strings with line breaks

Usually in javascript when we want to write a paragraph with line breaks between phrases we should add “ \n” at the end of each phrase , unless we do that , javascript doesn’t understand that it is a line break and will generate an error . See the example below :

Notice when we went to the next line , the rest of the paragraph is not colored in red like the first phrase and that’s because , like I said before , Javascript didn’t recognize that those strings belong to the same paragraph. The console.log didn’t show anything too . So what we usually do before es6 ? Well , we add “\n” at the end of each phrase where we want to have a line break . like shown in the example below :

As you see this is not practical and not well presented . ES6 came with the Template Literals to solve this problem . With this new feature all you got to do is write your string and whenever you want a line break you just go the next line and keep writing . Template literals are those symbols : ``

See this example for better understanding :

2. Concatenating phrases

To concatenate strings , we usually use the + operator in javascript

Now , with small phrases like these and limited number of variables , it may be okey to use the + operator , but as you notice , it is not very practical , not very fast and the more strings we have , the more it will turn into a mess .

ES6 introduced the Template Literals as a way to concatenate strings . In the example below , you have the same code but with a different version :

You write the strings between `` and whenever you have a variable to add , you put it inside this ${}

This is more practical , much easier and is presented in better format

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response