Tag Archives: Template Literals

JavaScript String Interpolation

Up till now in JavaScript, the only way to ever insert variable content into a string was to concatenate the string with the variable, ensuring that there was proper blank spaces around the text to ensure that it looked like a normal sentence :

var name = "Simon"; 
var age = 24;
var sentence = "Hi, my name is " + name + " and my age is " + age;

Other languages such as ruby, C# have had a handy little feature that allows placeholders to be used inside a string literal i.e. anything between the single or double quotes. This alleviated the long winded string + variable + string… formations.

ES6 (EcmaScript 6) brings this capability to JavaScript with String Interpolation. In similar fashion to languages that have had this feature already, it works by using template literals as placeholders within the quoted text:

var name = "John";
var age = "30";
var sentence = `Hi, my name is ${name} and my age is ${age}`;

Apart from the Template Literal – ${variable} – token, the other thing to take note is that back ticks “ are needed and not the usual single (‘ ‘) or double quotes (” “).