Menu Home

Template Literals

Hi everyone, and welcome to another thrilling adventure in Boring JavaScript! Today’s post will walk you through how to use Template Literals in defining strings.

Don’t like to read? Then check out our video!

It’s a Hot Mess

Take a look at the following code:

const animals = [
	"Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", "Dolphin", "Whale", "Lizard"
];

const cat = animals[0];
const dog = animals[1];
const horse = animals[2];

let myAnimals = "\nMy animals are a " + cat + ", a " + dog + ", and a " + horse + ".";
console.log(myAnimals);

// output
// My animals are a Cat, a Dog, and a Horse.

Line 9 is the OLD way we used to put together strings. It worked … but … it was very hard to read. So the JavaScript Rulers got together a number of years back and said ‘There has to be a better way’. And that better way is called ‘Template Literals’ or ‘Template Strings’.

Showing you is the best method to describe it, so let’s rework the above into a Template Literal.

const animals = [
	"Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", "Dolphin", "Whale", "Lizard"
];

const cat = animals[0];
const dog = animals[1];
const horse = animals[2];

let myAnimals = `\nMy animals are a ${cat}, a ${dog}, and a ${horse}.`;
console.log(myAnimals);

// output
// My animals are a Cat, a Dog, and a Horse.

Same things as before, but look at the change in Line 9. There are two important changes:

  • The backtick marks. The string is now enclosed by a ‘backtick’ mark, and not a single or double quote. JavaScript will see this and take everything from one backtick mark to the ending backtick – and I mean EVERYTHING – line feeds, special characters, everything – as part of the string. This is the ‘literal’ part of Template Literals.
  • The ${} construct. This will instruct JavaScript to insert a variable, named by what’s inside the curly-cue brackets, into the string literal. And it could be anything – a variable, a function name call, even a constant. This is the ‘template’ part of Template Literal.

And that’s it! Template Literals let you format strings in a MUCH MORE developer-friendlier way.

The Bells and Whistles

Did I mention the word ‘Everything’ in the above section? Take a look at this:

const animals = [
	"Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", "Dolphin", "Whale", "Lizard"
];

const cat = animals[0];
const dog = animals[1];
const horse = animals[2];

myAnimals = `
My animals are:
 1. One ${cat},
 2. One ${dog}, 
 3. One ${horse}.
 `;
console.log(myAnimals);
* output
My animals are:
  1. One Cat,
  2. One Dog, 
  3. One Horse.
*/
 

When I say it copies everything between the two backtick marks, I meant EVERYTHING. Look at Lines 9 through 14. Normally, JavaScript would cry “Foul” at this and refuse to run. But since each line of code is within the backtick marks, JavaScript will take it verbatim – including the line feeds. Proof of that can be seen in the output. The lines feeds in the original code are preserved in the string itself, and thus appear in the output.

Going Down the Rabbit Hole

Another great feature of Template Literals is the ability of embed literals within literals. The best way to show you is with an example:

const animals = [
	"Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", "Dolphin", "Whale", "Lizard"
];

const cat = animals[0];
const dog = animals[1];
const randomAnimal = animals[Math.floor(Math.random() * animals.length)];

const report = `I have a ${cat}, a ${dog}, and a ${randomAnimal == cat ? `duplicate ` : `unique `}${randomAnimal}`;
console.log(report);

// output 1
// I have a Cat, a Dog, and a unique Horse

// output 2
// I have a Cat, a Dog, and a duplicate Cat


Back to Line 9 again – this time there is a conditional as the JavaScript expression within the template. And within that expression, you can see additional backtick marks around “duplicate” and “unique”. What this means is that you can embed backtick marks within other backtick marks, and JavaScript can figure out what to do with them.

Personally, I feel this makes the code more complicated to read – about as bad as using the “+” sign to concatenate strings. But it can be a great tool if you need literals within your templates.

Tagging That Function

The JavaScript Gurus also gave us a new way to declare a function that is related to Template Literals, and that is the Tagged Function. Basically, it’s a function call that, instead of using parenthesis to pass arguments, it passed a Template Literal. The function itself then accepts arguments that include the static strings of the template, plus the variables passed. This allows you to control how the template literal is to be processed. Confused? Let’s take a look:

const animals = [
	{ type: "Cat", name: "Fluffy", size: "small" },
	{ type: "Dog", name: "Fido", size: "medium" },
	{ type: "Horse", name: "Mr. Ed", size: "big" },
	{ type: "Cow", name: "Betsy", size: "big" },
	{ type: "Coyote", name: "Wile E.", size: "medium" },
	{ type: "Road Runner", name: "Beep Beep", size: "small" },
	{ type: "Dolphin", name: "Flipper", size: "big" },
	{ type: "Whale", name: "Moby Dick", size: "huge" },
	{ type: "Lizard", name: "Larry", size: "tiny" }
];

function getReport(strings, animal) {
	if (animal) {
		return `
REPORT:
Animal collected: ${animal.type}
Animal name:      ${animal.name}
Animal size:      ${animal.size}
Comments:
	${strings.join(' ')}
`} else {
		return `
REPORT:
No animals to report upon.
Comments:
  ${strings.join(' ')}		
`
	}
}

const collectedAnimal = animals[Math.floor(Math.random() * animals.length)];
let report = getReport`We collected this animal in an alley behind the hospital. ${collectedAnimal}`;
console.log(report);

report = getReport`We found nothing.`;
console.log(report);

Line 33 shows how to call a Tagged Function. Notice that is does not have parenthesis, but instead replace the parenthesis and the arguments with a Template Literal.

The function itself (Line 13), is declared to have two arguments. The first argument is an array of strings representing each string in the passed Template Literal, while the second argument is the template variable inside of the template literal. If there are more than one variables, each one will be listed as additional arguments to the function definition. So you can have something like this:

function tagged(strings, arg1, arg2, arg3) {
    console.log(strings);
    console.log(arg1);
    console.log(arg2);
    console.log(arg3);
    return "We have received your request.";
}

const name = "Sally";
const purchase = "Bubble-gum";
const amount = "$1.75";
const report = tagged`Can you help me ${name} with ${purchase} for ${amount}?`;
console.log(report);

// output
// ['Can you help me', 'with', 'for']
// Sally
// Bubble-gum
// $1.75
// "We have received your request."

Notice that the tagged function can return anything – after all, it is a function. And this is the power of the tagged function. It allows you to take a Template Literal and do some serious processing on it before output the string (should you desire to do that).

The Video

As always, we have a video to accompany this article.

Shameless Plug

Check us out all over the web!

Check out all our videos at: https://www.boringjavascript.com
Check out everything at: https://www.thevirtuoid.com

Facebook: https://www.facebook.com/TheVirtuoid
Twitter: https://twitter.com/TheVirtuoid
YouTube: https://www.youtube.com/channel/UCKZ7CV6fI7xlh7zIE9TWqgw

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

%d bloggers like this: