Template literals in JavaScript

August 06, 2020

Earlier this week I asked people which piece of syntax they always find themselves Googling. My answer to that question was string literals in React. (I meant template literals, but we’ll get to that later.)

In response, I got a lot of people asking questions. Aren’t template literals an ES6 piece of syntax? Yes, they are.

What I should have said is that I always seem to mess up template literals INSIDE React. What’s the difference? Let’s talk about it!

“Just strings”

Template literals are a concept with many names! You may have heard them referred to as template strings, and then my combined version from from above 😅.

In some ways, template literals and strings can be the same thing. The following is considered a template literal.

const text = `some string`

That looks like it’s a regular string. The only difference is that it’s surrounded by backticks instead of quotation marks.

Multi-line strings

The reason this concept is more powerful than strings is because you can do more with it than the example above.

For instance, template literals allow for multiline strings.

const text = `some string line 1
and line 2 too`

How about an expression?

Template literals are popular not necessarily because of the two use cases above, but because of the fact that you can include expressions in them.

const text = `some string ${expression}`

An expression can be a lot of things. Some kind of string or number manipulation logic. Or, more commonly, a variable.

let name = getName()
const fullName = `some string ${name}`

So how is it different in React?

Why does this confuse me in React? Arguably it shouldn’t, it’s the same ES6 syntax. The reason I always seem to mess it up in React is because you can’t use a template literal directly when you pass it in a component.

<Component name=`some string ${name}`/>

The above code isn’t valid. In order to use that string literal, you have to surround it with curly braces.

<Component name={`some string ${name}`} />

It’s powerful code. Incredibly important and often used. But for me, it’s one too many characters to remember.

And?

So I look it up! And maybe in the future, I’ll look at this post instead. However, even if I can’t write it off the top of my head it’s invaluable to know what it is.

As with any piece of syntax, the more building blocks you know the more approachable it is to read code. It allows you to start to understand how the final codebase was put together.


A blog by Laurie Barth.
Teacher of all things tech.