Template Literals (aka String Interpolation) With a Backtick

String interpolation in ES6 with Backtick

One of the often-overlooked new features in ES6, formally known as ECMAScript 6, is string interpolation.

If you don’t know what interpolation means, you probably have seen it before didn’t realize it was called interpolation.

It’s important to understand that interpolation is a kind of string replacement, but it is a more specific kind. With a string replacement, we take some part of a string (a substring) and replace it with something.

Dear [FIRST],
We wanted to thank you for...

Here we have the template for a letter we could write. The symbol will be replaced by the person’s actual first name, and of course, in the context of a program doing this, we’ll do it again and again, each time putting in the next person’s name. That is called string replacement.

When we do it in coding, it is called interpolation. Specifically, we can insert not just a specific, non-changing marker (like [FIRST] or [LAST]), we can evaluate some code (in our case Javascript)

In the ES6 backtick string interpolation, Javascript is upgraded.

In ES5, if we wanted to create the first line above, we’d need to do semething like this:

var = "Dear " + first_name + ","

In ES5, you had to use ' and " to string together quotes and plus symbols to form dynamic content. That is called stringing things together (they must all be strings, either variables or literals) and is NOT interpolation. What makes it interpolation is that we don’t need to close our string, add a plus symbol, then type the variable, then another plus symbol, then re-open the string with another quotation mark, etc.

String interpolation turns the above into this, which introduces us to the backtick in Javascript

The backtick `

var = `Dear ${first_name},`

Notice that instead of straight quotes ” we use the backtick `. On American keyboards, the backtick is located to the left of the 1 key on the top row of keys. If you hold shift, this key instead types a tilde character (~).

Four Things To Note About Backtick Interpolation in ES6

  1. You can include carriage returns inside of the string, meaning the opening backtick and the closing backtick might be on separate lines.
  2. You use ${…} to do interpolation.
  3. You can use more than one ${…} in the same string
  4. If you write the backtick directly after (with no spaces) a function, you will call that function by passing the generated string.

Same Line Passing

This commonly will show up in ES6+ codebases:

realBindingCall`Lorem ipsum dor ameet

${props.name}, Ut lorem libero, placerat non ullamcorper varius,`

Here, we’re going to interpolate result of `Lorem ipsum dor ameet ${props.name}, Ut lorem libero, placerat non ullamcorper varius,` and then call the function realBindingCall, passing it the string as the argument.