JavaScript ES6: string interpolation

This small post is next about very nice ES6 features, next to post about arrow functions in JavaScript. In many cases we must concat many strings with variables in JS or other languages. For example to inject some data, URLs, names, params or just for display something on page or app. In the past, we have to use plus operator and concat everything in very, very messy way. With ES6 we can stop doing this and use strings interpolation. Similar to, for example PHP, we can put variables in the same line without additional operators. Please look at small examples.

First, example of traditional way and concat using plus operator, messy, and illegible:

let title = 'View Article' + article.name + ' - ' + category.name

It doesn’t look so bad, but imagine situation, then you have to put many variables and string is much longer. Or maybe you still use jQuery or other JS library and just generate HTML kode in JavaScript? Yeah, it will be terrible. With ES6 you can use string interpolation, and the best explanation will be next example:

let title = `View Article ${article.name} - ${category.name}`

Yep, it’s all. Much, much better, right? To use interpolation you have to replace ‘ and ” by ` and put all variables in form: ${myVariable}. You don’t have to use plus operator anymore, it will work without any issues.

There is additional benefit from using string interpolation: multilines support. With concatenation, you had to do this manually by adding new lines and it created additional mess. See this small example:

let text = "Lore ipsum is a text from " + base.name + ".\n"
	+ "The biggest number is " + biggestNumber + " and it won.\n"
	+ "You have to work " + workDays + " days per week."

It’s terrible not only because it’s illegible, but it’s very easy to make stupid mistake – forgot about quotation marks / apostrophes or new lines . With interpolation is much cleaner:

let text = `Lore ipsum is a text from ${base.name}.
	The biggest number is ${biggestNumber} and it won.
	You have to work ${workDays} days per week.`

Very practical, very human-friendly and fault tolerant.

Summarizing, interpolation is small, but very nice ES6 feature. It allows us to make code better, cleaner and easier to understand. Of course, as other ES6 feautres, it requires polyfills in some browser, so you should use JS bundlers.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.