JS Tip of the Day: Variables in Strings with Template Literals

Variables in Strings with Template Literals
Version: ES2015
Level: Beginner

It’s not uncommon that you’d need to add variable values into your strings. For example if you’re telling the user the results of a test, you might need to use something like:

let grade = 'A+';
let message = 'Your grade is ' + grade + '!';

Historically, this is how you would add values to a string, using the addition or string concatenation operator (+). But with the newer template literal syntax for strings, you no longer have to terminate the string, add what you want, then start up a new string up again, bridging them all together with + operators. Instead you can place a variable (or any expression, really) directly within the string using the interpolation syntax ${}.

let grade = 'A+';
let message = `Your grade is ${grade}!`;

Anything inside ${} in a template literal string (strings defined with `) will be evaluated and inserted into the resulting string at that location. This makes it much easier to insert values into your strings in a way that can also be easier to read.

Keep in mind, however, that this syntax does not work with strings defined with single or double quotes. It only works with template literal strings defined with backticks.

let grade = 'A+';
let message = `Your grade is ${grade}!`;
console.log(message); // Your grade is A+!

let quotedMessage = 'Your grade is ${grade}!';
console.log(quotedMessage); // Your grade is ${grade}!

More info:

1 Like