Adding Variables into Strings using JavaScript's Template Literals
December 20, 2020
If you've been browsing this series, or just trying out new parts of JavaScript, you've seen how console.log()
can be the quickest way to test your code as you work. You may (quite often) need to log the value of a variable and a label that makes the data more readable.
The +
operator is probably the most obvious way to tack strings together -- or concatenate them. When you first started out you probably guessed you could concatenate strings this way.
var label = 'value:';
var value = 'breakfast';
console.log(label + ' ' + value);
You might've used a similar approach to tack more strings together, for example to log two variables to the console.
var label = 'values:';
var values = [ 'breakfast', 'lunch' ];
console.log(label + ' ' + values[0] + ' and ' + values[1]);
Those methods of logging our variables are valid, but there is another syntax that you might find useful. It's called a template literal. One of its features allows us to include the values of variables in a string.
Template Literals
Let's use our second example above to demonstrate this. We want to log a string to the console that lists the two values in our array and labels for readability. Instead of enclosing our string in quotes as usual, we'll use backticks `
, aka grave accents or acutes. They look similar to single quotes, but they turn our string into a template literal.
Unlike regular strings, we can slot expressions directly into template literals, meaning that we can effortlessly pull values into our string. If we use ${
and }
to enclose the name of a variable, and that variable's value will be spliced into our string.
Let's use this to rewrite our example from this:
console.log(label + ' ' + values[0] + ' and ' + values[1]);
To this:
console.log(`${label} ${values[0]} and ${values[1]}`);
So we've removed a few +
operators and made the code more readable and easier to understand (now that you recognize a temperate literal syntax, that is). Template literals provide the opportunity for a more elegant syntax, though both console.log()
calls result in the same output:
values: breakfast and lunch
Last Word
Imagine putting this technique to use in updating displays: we can easily declare strings with variable data, from small spots like slotting in a user name, to bigger applications like displaying a blog post's tags, related articles, and other metadata.
Template literals provide other opportunities too, like multi-line strings and nesting. They're worth taking a deeper look into, but their ability to effortlessly concatenate strings with variables is useful in just about any JavaScript project. While template literals may be confusing if we don't recognize their syntax, they're a fantastic addition to our tool belt once we do!