Published: 2017/05/24 Reading Time: 1 minutes

Template Strings in JavaScript Are Awesome

Remember when concatenating strings in JavaScript was a royal pain your workflow? Well, my friend, with template strings, JavaScript is fun again! If you haven't started playing around with ES6 (ECMA Script 2015, the newer version of the JavaScript language), then this is probably one of my favorite features (there are lots of new JavaScript features in ES6).

The Old Way of Concatenating Strings

Just as a refresher, and to help the comparison a bit here, this is what you used to have to do in order to build a simple dynamic string:

const dynamicVariable = function (x, y) {
    return x + y;
};


let newString = "The dynamic variable is " + dynamicVariable(1, 2) + ", isn't that lame?!";
// Outputs: The dynamic variable is 3, isn't that lame?!

That's not bad when it's a tiny string like that, but what if you have several variables to parse in the string? Things can get messy pretty fast. Enter, template strings!

The Template Strings Way

Now, let's re-do the example above with ES6 template strings, and hopefully you'll see the awesome potential:

const dynamicVariable = function (x, y) {
    return x + y;
};


let newString = `The dynamic variable is ${dynamicVariable(1, 2)}, isn't that awesome?!`;
// Outputs: The dynamic variable is 3, isn't that awesome?!

In my opinion, this version of concatenating strings together with variables is much more readable, as well as easier to type. It's up to you, both ways still work — but now you know! The two things that make a template string are as follows:

  1. Start the template string with a back-tick: `.
  2. Variables to be parsed should be wrapped in the following: ${variable_here}
  3. End the template string with another back-tick: ` For now, it's probably best to still use a compiler like Babel to make this newer syntax older-browser compliant – but that's entirely up to you as well. Have fun!