DEV Community

gyi2521
gyi2521

Posted on

3 1

ES6 - Template Literals

The one of my favorite features in ES6 or ECMAScript 2015 is 'Template Literals'. Before I learn about 'Template Literals' in my Coding Boot-camp recently, I used to use string concatenation in JavaScript as following:

 
var user = {
  name: 'Gina',
  hobby: 'Traveling',

};

console.log('Hi, I\'m ' + user.name + '! My hobby is "' + user.hobby + '".');

//Hi, I'm Gina! My hobby is "Traveling".

Now with template literals, I can write as following:

var user = {
  name: 'Gina',
  hobby: 'Traveling',

};

console.log(`Hi, I'm ${user.name}! My hobby is "${user.hobby}".`);

//Hi, I'm Gina! My hobby is "Traveling".

Both examples give the same result, but do you see how readable the second example is using the 'Template Literals'? When you are using string concatenation, you need to use the backslash(\) to escape special characters. Because of the duplicate usage of some of the characters, reading and understanding the text could be challenging. With Template Literals, you construct the string as you are writing a plain English sentence inside back-ticks(``). If you want to add variables, just use a dollar sign followed by curly brackets. You can even add a simple Javascript statement if it is necessary as following:

console.log(`Two times seven is ${2*7}.`);

// Two times seven is 14.

In addition the line breaks got much easier with Template Literals.

With Template Literals:

console.log(`Hi Gina,
Good luck with your presentation today!
                          -your friend`)

//Hi Gina,
Good luck with your presentation today!
                          -your friend
Without Template Literals:

console.log('Hi Gina, \n' +
'Good luck with your presentation today! \n' +
'\t\t\t\t\t\t   -your friend')

//Hi Gina,
Good luck with your presentation today!
                          -your friend

Do you see how easy it is to read? With template literals, you create text as you write a note to your friend without using new line characters(\n) or tabs(\t). I have not encountered any issues with this feature so far and I really enjoy using it. If you have not tried it yet, you should definitely give a try...

Thanks for reading!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs