You've successfully subscribed to developer.school
Great! Next, complete checkout for full access to developer.school
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

JavaScript (ES6)+ : String Concatenation with Template Literals

Paul Halliday
Paul Halliday

Have you ever ran into code that looks something like this?

const firstName = "Paul"
const lastName = "Halliday"

const greeting = "Hello, my name is " + firstName + " " + lastName

// Hello, my name is Paul Halliday

In order to combine the firstName and lastName into a greeting, we're using the + operator.

Whilst this works in practice, it's kind of annoying because we have to manually add spaces, whitespace, and then remember to concatenate our next variable.

Thankfully, there's a better way to do this.

String Interpolation using Backticks

We can use the backtick `` (found next to Z or 1) on your keyboard instead of quotes to concatenate strings as seen here:

const firstName = "Paul"
const lastName = "Halliday"

const greeting = `Hello, my name is ${firstName} ${lastName}`

Inside of our backticks we're using the ${expression} syntax, where expression resolves to the function or variable that we want to show.

Browser support

As always, you should be careful about using any new syntax without a compilation step/polyfill.

Here's the list of browsers that support this syntax: https://caniuse.com/#feat=template-literals

JavaScript

Paul Halliday

👋 Want to see more content? Head over to the YouTube channel: https://youtube.com/c/paulhalliday!