Template strings are one of my favorite things about Javascripts es6 syntax. Why? First, we can inline javascript values inside our string. If we wanted to print our a variable or value, we would have to do the following in es5:
var myValue = 32;
console.log('this is my value: ' + myValue);
Okay, one plus to concatenate our value to the string , no big deal right?
What if we needed a larger string?
In es5, we would do the following:
var myString = "I am a very large string. This string could have " +
"Important information that we might need for whatever task we might"+ " have at hand.";
Note all the extra quotes and plus signs we have in our string. If the string needs a new line we must add a plus and concatenate it with a new string on the next line.
In addition, we might need to add a space at the end of each string if the next string is a new word and not a part just a continuation of a cut off word in the previous string.
Now let us combine these two issues with es5 strings into one potentially big confusing issue.
var var1 = "hello";
var var2 = "world";
var var3 = "master;
var numberOfPeople = 1
var confusingString = "Hey everyone, I just wanted to say " + var1+
"! I cant believe I'm finally making my " + var2 + " debut! I'm "+
"not trying to act like I'm a " + var3 + " of coding but even "+
"if i could help " + numberOfPeople + " person this will all be wor"+ "th it.";
That string was really a mouth full, we had to add a total of 11 plus signs!
We can make this confusing string less confusing using template literals
var var1 = "hello";
var var2 = "world";
var var3 = "master;
var numberOfPeople = 1
var confusingString =
`Hey everyone, I just wanted to say ${var1}! I cant believe I'm finally making my ${var2} debut! I'm not trying to act like I'm a ${var3} of coding but even
if i could help ${numberOfPeople} person this will all be worth it.`;
You might be wondering why I wrapped ${ }
around the variables in our string instead of concatenating them with a +
sign. This is one of the benefits of template literals, we can add variables into our strings using this syntax to add our variables without worrying about all the plus signs we would have to deal with!