When we work with strings in JavaScript, one of the first things we learn is concatenation. Concatenating involves joining the content of two expressions (strings). In JavaScript, the operator for concatenating is the plus sign (+). For many years, this was the only way we had to perform concatenation.
However, with the release of ECMAScript 6, or ES2015, we received new help to perform not only string concatenation but also variable interpolation: we got Template Strings. With them, it became much easier to even display the value of variables in our texts.
To create a template string, we must use the backtick (`). You can trigger it with Shift + ´ on Windows or Option + ´ on Mac. To access variables, just use the dollar sign ($) along with braces and the variable name between them.
Let's look at two examples of how practical template strings are.
Example 01 - Display values of a simple object in the console
See this code:
With it, we created an object called user and are displaying its values through console.log(). Let's see the result:
Notice that the values of the variables are correctly identified and displayed. But did you notice how we need to type the plus sign (+) multiple times and also open and close quotes repeatedly? This can confuse us when working with a lot of information. See how this same code would look with Template Strings:
The result will be the same, but see how much easier it is to read the code, much simpler and easier to understand.
Example 02 - Build the HTML content of a table dynamically
Now let's create the content of a table that will display the value of the variables from our object using the “classic” concatenation. See how the code will look:
Notice that the variables are the same as in the last example. The result will be:
Cool, the table was created correctly. However, again we notice the issue of many plus signs in the string, in addition to needing to open and close quotes on every line break. Now see it with Template Strings:
Incredible, isn't it? Our code is much cleaner. If it's easier to read, it was certainly easier to develop as well.
These two examples showed how Template Strings are truly amazing. So, if you can, use them in your projects, you won’t regret it.
JavaScript has evolved a lot in recent times, and it's good to be able to keep up with its innovations that keep raising the level of this language more and more.
Don’t forget to subscribe to our channel on Youtube to receive cool web development content in video format as well, until the next article.
Did you like this article?
Would you like to learn more about JavaScript? Then subscribe to our Complete JavaScript Course. Learn from two experts about the various features of this language, with real projects and the Hcode teaching method ;)