I can ES6 and so can you! Pt. 2: Template Literals

One of the best ways to increase your vocabulary is to learn a new word everyday and try to incorporate it into your daily conversations with other fellow humans or the uncommon imaginary friend. So, in this series, I will present a single bite-sized piece of ES6 in every mini blog for your eyes to consume. I hope you floss, because much of it is syntactic sugar. Keep up every day, and you’ll be confusing your colleagues with your newfound alien syntax in no time! What fun!

Concatenating long strings has always been a source of stress for me. Double quotes or single quotes? Did I add enough plus signs? What characters do I need to escape to make this damn thing work!?

Well, no more! Today, we learn about template literals. Traditionally, we would concatenate a string like so:

var name = 'Your name is ' + first + ' ' + last + '.'
var url = 'http://localhost:3000/api/messages/' + id

Familiar? Well, ES6 introduces a new syntax in which you can lose the addition operator along with the quotes. All you have to do is encase a variable like this:

` ${Variable}`

In use, our example would look like this:

var name = `Your name is ${first} ${last}.`
var url = `http://localhost:3000/api/messages/${id}`

Also, note the whole string is surrounded by back ticks. That’s the brand new looking button you see located to the left of your 1 button.

Like what you read? Give David Nguyen a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.