DEV Community

George Hanson
George Hanson

Posted on • Originally published at

Turbocharge JavaScript strings with Template Literals

Anyone who has been writing JavaScript for a long time will know it has come on leaps and bounds. ES6 has been out for a while now, but there are still a lot of features that I see developers either forgetting or not realising they exist.

Today I'm going to show one of my personal favourites, template literals!

Before ES6

In the old-un days back when we used to use jQuery for absolutely everything, string concatenation was fairly limited. If we wanted to construct a string it got messy, quite quickly. Here is an example.

var person = {
  name: 'George',
  age: 23,
  location: 'England'

var sentence = 'Hi, my name is ' + + '. I am ' + person.age + ' years old and I live in ' + person.location

While this works, it looks messy. If something can be tidied up and made more readable, personally I think it is worth it.

After ES6

When ES6 arrived it brought a bunch of features with it. Template literals allow you to easily construct these strings without making the concatenation look too messy.

Let's take the same example above. How might we do this using ES6 template literals? Well, it is very simple. Below is how we would do the exact same thing but in a more readable way.

let person = {
  name: 'George',
  age: 23,
  location: 'England'

let sentence = `Hi, my name is ${}. I am ${person.age} years old and I live in ${person.location}.`

As you can see with template literals we no longer have to use quotes or + operators to concatenate the string. Instead, we can just use ${ and }. I feel like this is a really nice improvement.

In order to use template literals, you'll notice that we use back-ticks rather than quotes. This is also useful because it means we no longer need to escape quotation marks in the string. For example, without using template literals we would have to do this:

let greeting = 'Hello! I\'m pleased to meet you!'

But with template literals, we aren't using quotation marks to denote a string. So we can just include them without having to escape them.

let greeting = `Hello! I'm pleased to meet you!`

One final point I'll make, you can also evaluate expressions within template literals. For example, if I wanted to double the person's age I could write this:

let sentence = `Hi, my name is ${}. I am ${person.age*2} years old and I live in ${person.location}.`

I hope you find this useful, I find myself using template literals all of the time.

This article was originally posted here:

Top comments (0)