Facerolling With ES5 String Concatenation
In ES5, templating with strings isn’t much fun at all. You can follow best practices and make life a little bit easier. There isn’t much to get excited about though.
Basic String Concatenation In ES5
It is a bit annoying how many ‘s and +s you have to use just to form such a short sentence. It doesn’t make your code very readable. There are a lot of extra characters just to output a simple string. The issue only compounds the longer the string is that you want to build.
Multi-line String Concatenation In ES5
If you have a long string you want to concatenate in ES5 then you must use the \ like so:
This method is as close as you get to something like PHP’s heredoc syntax. It still falls short, and you still have to use the ‘ and + along with your \. Ugh! It looks and feels so nasty.
Hackery With array.join()
Another trick I’ve used in the past when creating strings for use with templating engines is the array.join( ‘\n’ ) method:
With this method, every new line is an element within in an array. You then join them all together to form one string. The above example uses Underscore.js template variables to pass in the dynamic values.
New ES6 String Templates Are Sweet
Concatenation and templating are a whole lot easier with ES6 string templates.
Creating An ES6 String Template
To create a string template all you have to do is wrap it in backticks (`):
Easy right? The hardest part is not mistaking the backtick for a single quote. Perhaps overcoming muscle memory from wrapping strings with single quotes for years will take a few days as well. Now let’s get into the good stuff you can do with them.
New Lines And Whitespace Are Free With ES6 String Templates
With ES6 string templates, you don’t have to worry about managing new lines or whitespace. They are both respected within the templates with any extra work. You can even use tabs.
Interpolation With ES6 String Templates
What would templates be without an easy way to pass in dynamic data? ES6 string templates support interpolation of variables for outputting dynamic values into your templates. This feature is one of my favorite parts.
Remember the greetUser() function above in the first code example?
We can rewrite it like so:
No more +s and ‘s. You get the same output and t is much easier to envision the final result of the string. Code readability levels up!